在指令工作不选择输入的双向绑定 [英] Two way binding of select input in a directive not working

查看:134
本文介绍了在指令工作不选择输入的双向绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个指令来选择输入选择一个用户ID。该模型从指令到视图的其余部分结合。然而,当我从控制器设置id似乎不绑定的指令来选择输入。

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.

控制器:

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的

index.html

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

  userId = {{userId}}
  </body>

directive.html

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

Then the binding will work. See updated plnkr

修改,关于注释以下问题:

请你解释一下,为什么它不与NG重复的工作?

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>

即。我们增加了 NG-选择=user.id === ngModel

但是,这有一些缺点。首先,您要创建不需要隔离范围。而且,绑定选项的值是字符串,即你会真正选择 1 '2'3而不是 1 2 3

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.

这篇关于在指令工作不选择输入的双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆