Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ng-model bound from nested ng-repeat

This must have been already done, and I am missing something about how Angular works on that point.

In short, I have <select ng-model><option ng-repeat/></select> and I don't know how to give it a default value at page load.

View:

<div ng-ctrl="MyCtrl">
  <form ng-submit="submitChoice()">
    <select ng-model='choice'>
      <option ng-repeat='choice in choices' value='{{choice.id}}'>{{choice.id}}</option>
    </select>
  </form>
</div>

Way 1: When user updates the view (select the 'choice' he wants), the $scope used in MyCtrl gets it and I can perform whatever I want with it:

Way 2: But if, the other way round, I want to programmatically set the default value for the choices from the controller (at start), it can't change the value displayed:

function MyCtrl ($scope) {
  $scope.submitChoice = function() {return;}; // Way1: OK!
  $scope.choice = choice4;                    // Way2: Doesn't change the view!!
}

I guess it's because each element in ng-repeat has its own scope (fyi if I hardcode options in view instead of a ng-repeat, it works well).

In way 1 the inner scope selected by the use emits choice to the upper scope, if I understand well. But I have no idea how to do way 2.

Is it doable in a simple way? Is a directive necessary?

like image 659
lajarre Avatar asked Jan 20 '13 14:01

lajarre


1 Answers

You would be better off using the ng-options directive with the select directive. Using select + ngRepeat has all sort of limitations and is better avoided. Is there any particular reason for generating options with ngRepeat?

If you could share more code (especially the structure of your data model) I might be able to provide more info.

like image 137
pkozlowski.opensource Avatar answered Sep 20 '22 01:09

pkozlowski.opensource