How we set to ng-model variable to parent controller in nested controllers scope

≡放荡痞女 提交于 2019-12-11 11:23:56

问题


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>

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,
        },

How can i tell angular, that selectedObject model belongs to MyCtrl, and not CountryDataController. I tried

selectedObject="MyCtrl.country"
selectedObject="country[MyCtrl]"

but without effects.

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.

Is there any convention for this?


回答1:


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>



回答2:


The answer is:

selectedobject="$parent.country"


来源:https://stackoverflow.com/questions/28618337/how-we-set-to-ng-model-variable-to-parent-controller-in-nested-controllers-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!