简体   繁体   中英

Using AngularJs ControllerAs approach, How can I call a function in a parent controller from the child controller?

I know you may have seen this question before, but is there really an answer for it? I started to doubt it. Simply, I am using controlleras syntax as recommended, I have no problem accessing parent controller members form within the view, but I cannot do it from the constructor function of my child scope. And here is some code from what I am having right now:

  myapp.controller("ParentController", function() { this.selectedItem = { Id: 1, name: 'item1' }; this.setSelectedItem = function(item) { this.selectedItem = item; //do other stuff } }); myapp.controller("ChildController", function() { this.onItemChanged = function(newItem) { //How can I call the parent controller instance from here } }); 

Also please notice that I want to call the 'updateSelectedItem' function from my child controller in away that the 'this' keyword will refer to the parent controller instance not the child, because I want to change the parent controller instance, so how should I do this?

To answer your question as clearly as possible, you first must have a bit of background on how the Controller-As syntax actually works.

Using Controller-As does not mean that you are not using $scope . In reality, $scope still exists. Controller-As is shorthand which creates an object on $scope and attaches the properties assigned via this to that object. On the view side, this object is explicitly bound to all the controls. you could still reference $scope.vm.property . However, since $scope is implicit in this scenario, it is not necessary to create a dependency to it.

Accessing the properties of the vm object of the parent controller in a nested scenario is still possible, but only if each controller is referenced by a different name. If your objects are outerScope and innerScope , then inside the HTML template of innerScope , you can still refer to outerScope.someProperty .

If, however, all controllers are named the same (ie vm ), then the only way to access the parent controller would be through a property of the child scope which is aliased to a $scope property, introducing the $scope dependency.

In practice, whenever you have a controller within another controller, it's much cleaner for the innermost item to be a directive which wraps its own content, and explicitly defines which variables it needs through an Isolate Scope. However, whenever this is not necessary, the fallback should be for inner controllers to be named uniquely from outer controllers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM