我们如何设置为NG-模型变量在嵌套控制器范围父控制器 [英] How we set to ng-model variable to parent controller in nested controllers scope
问题描述
我有嵌套在另一个控制器范围1纳克控制器。
我想设置范围的变量在嵌套的控制范围,父控制器。
我的看法:
I have one ng-controller nested in another controllers scope. I want to set scope variable in nested controller scope, to parent controller. I have view:
<div ng-controller="MyCtrl">
<input type="text" ng-model="name"/>
<div ng-controller="CountryDataController">
<angucomplete
(...)
selectedObject="country"/>
</div>
</div>
这是形式的一部分。
然后在表单提交我想从 MyCtrl (姓名,国家)派纳克的模型做的:
which is part of the form. Then on form submit i want to send ng-models from MyCtrl ( name,country) doing:
fields: {name: $scope.name,
country: $scope.country,
},
我怎么能告诉角度,即selectedObject新型属于MyCtrl,而不是CountryDataController。
我试过
How can i tell angular, that selectedObject model belongs to MyCtrl, and not CountryDataController. I tried
selectedObject="MyCtrl.country"
selectedObject="country[MyCtrl]"
但没有效果。
在selectedObject工作angucomplete像NG-模式。
此外,我不希望从CountryDataController重写逻辑MyCtrl,因为在第一次我有自动完成,并在第二个文件上传域。
selectedObject in angucomplete works like ng-model. Also I don't want to rewrite logic from CountryDataController to MyCtrl, because in first i have fields for autocomplete and in second file uploading.
有什么约定吗?
推荐答案
您可以使用 $父
,但如果你移动你的HTML或最终添加其他控制器它,它的将中断。
You can use $parent
, but if you move your HTML or eventually add another controller it between it will break.
要做到这一点,正确的方法是使用控制器
语法,如下所示:
The correct way to do that is to use the controller as
syntax, as shown below:
<!-- use topCtrl to access this controller scope -->
<div ng-controller="MyCtrl as topCtrl">
<input type="text" ng-model="name"/>
<!-- use countryCtrl to access this controller scope -->
<div ng-controller="CountryDataController as countryCtrl">
<angucomplete
(...)
selectedObject="topCtrl.country"/>
</div>
</div>
这篇关于我们如何设置为NG-模型变量在嵌套控制器范围父控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!