我最近花了 4 个多小时才弄清楚为什么我的 ng-model
与 ng-options
结合使用的指令未正确绑定(bind)到我的 Controller 内的属性。 <select>
元素已正确初始化 - 从 Controller (父)范围接收值。但子作用域未正确更新父作用域。在检查了以下问题和插件之后,我能够为这个问题开发一个“解决方法”:
Helpful stackoverflow question 1
Helpful stackoverflow question 2
我发现我在 <select>
中绑定(bind)的属性元素绑定(bind)到 Controller 的子范围内的同名属性 - 因此该值未按预期反射(reflect)在 Controller 的范围中。更改后
<select ng-options="asset as asset.Name for asset in allAssets" ng-model="selectedAsset" ng-change="lookupAssetPermissions()"></select>
到
<select ng-options="asset as asset.Name for asset in allAssets" ng-model="$parent.selectedAsset" ng-change="lookupAssetPermissions()"></select>
selectedAsset
中的值已正确绑定(bind)到 Controller 范围内的属性(如 ng-change
事件处理程序中所示)。我的元素的整个上下文如下:
<!---outer div has controller level scope----->
<div>
<!---inner div creates child scope with ng-if----->
<div ng-if="true condition here">
<!---select statement from above----->
<select ng-model="$parent.selectedAsset">...</select>
</div>
</div>
在这种情况下,除了有目的地绑定(bind)到父作用域之外,我还有其他选择吗?如果我有多个子作用域(嵌套 ng-if
语句),我是否需要更改 ng-model
绑定(bind)到$parent.$parent.$parent....selectedAsset
为了更新我的 Controller 范围中的值?关于这个主题有什么“最佳实践”吗?
最佳答案
将所有变量放入某个对象中,即:
$scope.Model = {
selectedAsset : 'mySelectedAsset1',
selectedAsset2 : 'mySelectedAsset2',
selectedAsset3 : 'mySelectedAsset3'
}
然后你可以:
<div ng-repeat> //new scope
<div ng-repeat> // new scope
<input ng-model="Model.selectedAsset">
这也降低了您对 $scope 的“依赖性”,定义这样的 Model 对象将向正在阅读您代码的每个人显示您拥有的模型。
关于javascript - AngularJs 避免范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29413480/