FarazShuja
FarazShuja

Reputation: 2370

Calling child controller's method

I have two controllers like this

<div ng-controller="ParentController">
    <div ng-controller="ChildController">
    ... my grid table ..
    </div>
</div>

js code

function ParentController($scope) {
 ...
 $scope.refreshBtnClicked = function() {
    //here I want to call refreshGrid method of ChildController
 }
}
function ChildController($scope) {
 ...
 $scope.refreshGrid = function() {
 ... its using some inner variables of Child controller...
 }
}

How can I call it?

Upvotes: 0

Views: 176

Answers (3)

z.a.
z.a.

Reputation: 2777

Try this way, you will have to implement your service function but that's basically grid stuff.

<div ng-controller="ParentController">
    <div ng-controller="ChildController">
    ... my grid table ..
    </div>
</div>

function ParentController($scope, gridService) {
 ...
 $scope.refreshBtnClicked = gridService.refresh();
}
function ChildController($scope, gridService) {
 ...
 do whatever you like with your gridService methods or properties.
}

your factory or service 
angular.module('myApp')
  .service('Gridservice', function Gridservice() {
    //data and methods here
  });

you can also use broadcast or emit to trigger events, between controllers. like if you refresh, also your childcontroller data gets updated.

Upvotes: 1

z.a.
z.a.

Reputation: 2777

Well, you would have to do these things the AngularJS way. If there is a method or idea you want to share across controllers, you should implement it as a factory or service. And then you can use emit or broadcast to simultaneously share this service between controllers.

Can one controller call another?

Upvotes: 0

Mosho
Mosho

Reputation: 7078

With directives, you can "register" the child controller or scope in the parent. Something like this:

app.directive('parent', function(){
    controller: function(){
        this.children = [];
        this.addChild = function(childScope){
            this.children.push(childScope);
        }
        this.callChildFunc = function(childID){
            children[childID].someFunc();
        }
    };


})


app.directive('child', function(){
    require: '^parent',
    link: (scope, elem, attrs, parentCtrl) {
        parentCtrl.addChild(scope)  
        scope.someFunc = function(){};
    }
})

The child calls a function that adds a reference to its scope in the parent so it can call its functions. Another option would be to use $scope instead of this in the parent's controller and pass the addChild function to the child's scope using an isolate scope.

Upvotes: 0

Related Questions