1

In order for ASP.NET MVC to correctly bind a list of items on a form post, the name attribute has be along the lines of

name='Show.Days[0].OpenHour'
name='Show.Days[1].OpenHour'

The user can enter the number of days the show will be into a form field, which then updates the model and the ng-repeat. I'd like to be able to insert the appropriate index into the name field, something like

name='Show.Days[$index].OpenHour'

Is this possible with angular?

5
  • Should be possible,did you try it? Commented Mar 7, 2016 at 3:20
  • @SatejS I did yes, when I inspect the elements in Chrome, it just shows [$index] Commented Mar 7, 2016 at 3:22
  • did you try with name="{{Show.Days[$index].OpenHour}}" Commented Mar 7, 2016 at 3:23
  • @AndrésEsguerra just tried that, spits out the name attribute with no value Commented Mar 7, 2016 at 3:29
  • 1
    @AndrésEsguerra Ah, but you led me down the right path name="Show.Days[{{$index}}].OpenHour" works. If you want to post that as an answer, I'll mark it as the correct one. I have another angular question over here if you're feeling ambitious :) Commented Mar 7, 2016 at 3:32

2 Answers 2

6

Use name="Show.Days[{{$index}}].OpenHour". With this, AngularJS evaluates $index and replaces it with the correct value.

Sign up to request clarification or add additional context in comments.

Comments

1

It seems that you forgot to wrap the expression with {{ and }} in the view. Do you need something like this?

var app = angular.module('myApp', []);

app.controller("myCtrl", function ($scope) {
    $scope.Show = {
      Days: [
        {OpenHour: '8am'},
        {OpenHour: '10am'}
      ]
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <div ng-repeat="day in Show.Days">
      <input type="text" ng-model="Show.Days[$index].OpenHour" name="{{Show.Days[$index].OpenHour}}">
    </div>
  </div>
</div>

or like this?

var app = angular.module('myApp', []);

app.controller("myCtrl", function ($scope) {
    $scope.Show = {
      Days: [
        {OpenHour: '8am'},
        {OpenHour: '10am'}
      ]
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <div ng-repeat="day in Show.Days">
      <input type="text" ng-model="Show.Days[$index].OpenHour" name="Show.Days[{{$index}}].OpenHour">
    </div>
  </div>
</div>

3 Comments

The second one, name="Show.Days[{{$index}}].OpenHour" works
@MichaelTranchida It seems I am a bit late
Gotta be quick like a rabbit on SO, thank you though :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.