AngularJS:选择不是 2 路绑定到模型 [英] AngularJS: Select not 2-way binding to model

查看:24
本文介绍了AngularJS:选择不是 2 路绑定到模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用选择来显示客户名称.用户应该能够选择现有客户端,然后更新范围属性:

I am using a select to show Client names. A user should be able to select an existing client, which will then update the scope property:

控制器

初始化首选".

if($scope.clients.length > 0) $scope.existingClient = $scope.clients[0];

查看

<select
    id='nm-existing-client-name'
    class='form-control  input-lg'
    ng-model='existingClient'
    ng-options="client.name for client in clients">
</select>

范围属性 existingClient 在选择菜单更改时不会更改.如果没有初始化任何值(上面的控制器行被删除),existingClient 的值将保持未定义.

The scope property existingClient does not change when the select menu changes. If no value is initialized (controller line above is removed), the value of existingClient will stay undefined.

附加 ng-change 将在值更改时触发,但模型本身不会更新为新值.

Attaching an ng-change will fire when a value changes, but the model itself will not update to the new value.

我正在使用 AngularJS v1.2.0-rc.3.

推荐答案

我认为您可能正在使用子作用域并且不知道它.ng-ifng-repeatng-switchng-include 都创建了子作用域.作用域上的值是继承的,但是如果您更改子作用域中的值,它会在子作用域上设置一个值,并使父作用域上的继承值保持不变.尝试使用一个对象来保存您的值,看看是否可以修复它.由于您只是在对象上设置属性,而不是直接在作用域上设置值,因此它将使用父作用域的继承对象并更新值.

I think you are probably using a child scope and don't know it. ng-if, ng-repeat, ng-switch and ng-include all create child scopes. Values on your scope are inherited, but if you change the value in a child scope it sets a value on the child scope and leaves the inherited value unchanged on the parent. Try using an object instead to hold your values and see if that fixes it. Since you are only setting a property on an object and not a value directly on the scope it will use the parent scope's inherited object and update the value.

$scope.data = {
    existingClient: $scope.clients.length > 0 ? $scope.clients[0] : undefined
};

查看:

<select ng-model="data.existingClient" 
        ng-options="client.name for client in clients">
</select>

您可以使用 AngularJS Batarang 扩展程序在 chrome 中帮助调试范围.

You can use the AngularJS Batarang extension in chrome to help debug your scopes.

这篇关于AngularJS:选择不是 2 路绑定到模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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