AngularJS:不选择2路结合模型 [英] AngularJS: Select not 2-way binding to model
问题描述
我使用的是选择显示客户的名称。用户应当能够选择现有的客户端,然后将更新范围的属性:
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>
的scope属性 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-变化
将火当数值改变,但模型本身不会更新到新的价值。
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-如果
, NG-重复
, NG-开关
和 NG-包括
所有创建子作用域。在你的范围值是继承的,但如果你在孩子的范围更改值它设置对孩子的范围值,并离开了继承值父不变。尝试使用对象,而不是持有你的价值观,看看能否解决。既然你只在范围直接设置一个对象的属性,而不是一个值,它将使用父作用域继承的对象,并更新值。
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在Chrome扩展Batarang 帮助调试你的作用域。
You can use the AngularJS Batarang extension in chrome to help debug your scopes.
这篇关于AngularJS:不选择2路结合模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!