Two way binding of select input in a directive not working

爱⌒轻易说出口 提交于 2019-12-23 01:15:07

问题


I've created a directive for a select input to select a userId. The model binds from the directive to the rest of the view. However, when I set the id from the controller it doesn't seem to bind to select input in the directive.

Controller:

app.controller('MainCtrl', function($scope) {
  // set userId to willem's Id
  $scope.userId = 3;
});

Directive:

app.directive('selectUser', function() {
  return {
    restrict: 'E',
    scope: {
      ngModel: '='
    },
    controller: function($scope) {
      $scope.users = [{
        "id": 1,
        "name": 'Tupac'
      }, {
        "id": 2,
        "name": 'Biggie'
      }, {
        "id": 3,
        "name": 'Willem'
      }];
      },
    templateUrl: 'directive.html'
  };
});

index.html

  <body ng-controller="MainCtrl">
    users:
  <select-user ng-model="userId"></select-user>

  userId = {{userId}}
  </body>

directive.html

<select class='form-control focus' ng-model="ngModel">
    <option value="">all users</option>
// doesn't bind from the controller. Supposed to show willem, instead of all users to start with.
    <option ng-Repeat="user in users" value="{{user.id}}">{{user.name}}</option> 
</select>

Working example on: http://plnkr.co/edit/c7eyoB


回答1:


You should use ngOptions :

<select class='form-control focus' ng-model="ngModel" ng-options="user.id as user.name for user in users">
    <option value="">all users</option>
</select>

Then the binding will work. See updated plnkr


Edit, concerning the following question in comment :

could you please explain, why it is not working with ng-repeat?

You can achieve the same visual result with :

<select class='form-control focus' ng-model="ngModel">
  <option value="">all users</option>
  <option ng-repeat="user in users" value="{{user.id}}" ng-selected="user.id === ngModel">{{user.name}}</option>
</select>

I.e. we added ng-selected="user.id === ngModel".

But this has some drawbacks. First, you are creating unneeded isolated scopes. And also, the values bound to the options are strings, i.e. you will actually select '1', '2' or '3' instead of 1, 2 or 3.



来源:https://stackoverflow.com/questions/29195511/two-way-binding-of-select-input-in-a-directive-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!