且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

指令中选择输入的两种方式绑定不起作用

更新时间:2023-02-27 07:38:54

你应该使用 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'123.

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.