指令中选择输入的两种方式绑定不起作用 [英] Two way binding of select input in a directive not working
问题描述
我为选择输入创建了一个指令来选择用户 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
<body ng-controller="MainCtrl">
users:
<select-user ng-model="userId"></select-user>
userId = {{userId}}
</body>
指令.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-repeat 一起使用?
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-selected="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屋!