How we set to ng-model variable to parent controll

2019-07-27 21: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"