Search code examples
javascriptangularjsangularjs-directiveangular-ngmodel

ngRepeat-ed directives representing fields of external model


Let obj be an object in my $scope having an initially empty parts array property. I defined a scope function to add empty objects inside the parts array, and there's an ng-repeating directive (over the parts array) which in turn contains another ng-repeating one over the fields describing a single part instance (for simplicity, only two properties are taken into account, id and description, but in my actual scenario there are plenty more). According to the field's type property, it is either rendered as a <select> or an <input> tag. Ideally, the <select> should fetch from a list of possible parts, and bind the chosen one (both its id and description fields) to the current part in obj.parts, whereas the description field should offer a default description the user can further modify. But I can't get it to work. I jotted down this jsFiddle to better illustrate my issue.

If I click "Add part" and choose "foo" from the <select>, I expect:

  1. the first (and only) element in the $scope.obj.parts array to change to {"id":"foo","description":"Foo description"};
  2. the <input> field next to the <select> to display the description accordingly;
  3. the array element's description property to change If I edit the <input>.

Note: if I change (line 9 of the jsFiddle) the binding from ng-model="part" to ng-model="obj.parts[$index]", point 1. of the previous list works, but only on the array's first element (i.e.: if I add more parts, they all refer to $scope.obj.parts[0]) and issues 2. and 3. remain (actually, all <input>s refer to $scope.obj.parts[1].description, for some reason).

Please help, I'm at wit's end. Cheers.


Solution

  • Got it to work using the $parent scope identifier on both the obj.parts array and the outermost $index property. jsFiddle here.