How to call a function from another controller in

2019-01-04 08:34发布

I need to call function in another controller in angular js.How it is possible way please help me thanks in advance

Code :

app.controller('One', ['$scope',
    function($scope) {
        $scope.parentmethod = function() {
            // task
        }
    }
]);
app.controller('two', ['$scope',
    function($scope) {
        $scope.childmethod = function() {
            // Here i want to call parentmethod of One controller
        }
    }
]);

6条回答
三岁会撩人
2楼-- · 2019-01-04 09:06

Communication between controllers is done though $emit + $on / $broadcast + $on methods.

So in your case you want to call a method of Controller "One" inside Controller "Two", the correct way to do this is:

app.controller('One', ['$scope', '$rootScope'
    function($scope) {
        $rootScope.$on("CallParentMethod", function(){
           $scope.parentmethod();
        });

        $scope.parentmethod = function() {
            // task
        }
    }
]);
app.controller('two', ['$scope', '$rootScope'
    function($scope) {
        $scope.childmethod = function() {
            $rootScope.$emit("CallParentMethod", {});
        }
    }
]);

While $rootScope.$emit is called, you can send any data as second parameter.

查看更多
虎瘦雄心在
3楼-- · 2019-01-04 09:12

You may use events to provide your data. Code like that:

app.controller('One', ['$scope', function ($scope) {
         $scope.parentmethod=function(){
                 $scope.$emit('one', res);// res - your data
         }
    }]);
    app.controller('two', ['$scope', function ($scope) {
         $scope.$on('updateMiniBasket', function (event, data) {
                ...
         });             
    }]);
查看更多
贼婆χ
4楼-- · 2019-01-04 09:14

If the two controller is nested in One controller.
Then you can simply call:

$scope.parentmethod();  

Angular will search for parentmethod function starting with current scope and up until it will reach the rootScope.

查看更多
我命由我不由天
5楼-- · 2019-01-04 09:15

I wouldn't use function from one controller into another. A better approach would be to move the common function to a service and then inject the service in both controllers.

查看更多
Root(大扎)
6楼-- · 2019-01-04 09:15

The best approach for you to communicate between the two controllers is to use events.

See the scope documentation

In this check out $on, $broadcast and $emit.

查看更多
Rolldiameter
7楼-- · 2019-01-04 09:26

If you would like to execute the parent controller's parentmethod function inside a child controller, call it:

$scope.$parent.parentmethod();

You can try it over here

查看更多
登录 后发表回答