指令中选择输入的双向绑定不起作用

Two way binding of select input in a directive not working

本文关键字:绑定 不起作用 选择 输入 指令      更新时间:2023-09-26

我为select输入创建了一个指令来选择userId。该模型从指令绑定到视图的其余部分。然而,当我从控制器设置id时,它似乎不会绑定到指令中的选择输入。

控制器:

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

指令:

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>

工作示例:http://plnkr.co/edit/c7eyoB

您应该使用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>

然后绑定就可以工作了请参阅更新的plnkr


编辑,关于评论中的以下问题:

你能解释一下,为什么它不适用于ng repeat吗?

您可以使用获得相同的视觉效果

<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>

即我们添加了ng-selected="user.id === ngModel"

但这也有一些缺点。首先,您正在创建不需要的隔离作用域。此外,绑定到选项的值是字符串,即您实际上将选择'1''2''3',而不是123