Call a method from one controller defined inside a directive in another controller: AngularJS

I have a directive where a controller exists where I have a function. I need to call this function from another controller.

Directive:

    angular.module('test.directives').directive("manageAccess", function() {
        return {
            restrict: "E",
            replace: true,
            templateUrl: "template/test.html",
            controller: function($scope, $element, $http) {
                $scope.getRoles = function() {
                    console.log('hi');
                };
            }
        };
    });

      

$ scope.getRoles is the method that I need to call from another controller.

Controller:

    angular.module("test.controllers").controller("testController", function($scope, $http) {
        $scope.getUsers = function() {
            // i need to call getRoles method here
        }
    });

      

How can i do this?

Please help, Thanks.

+3


source to share


3 answers


Try to run

angular.module('test.directives').directive("manageAccess", function() {
        return {
            restrict: "E",
            replace: true,
            scope: {getRoles: '='},
            templateUrl: "template/test.html",
            controller: function($scope, $element, $http) {
                $scope.getRoles = function() {
                    console.log('hi');
                };
            }
        };
    });

      

controller



angular.module("test.controllers").controller("testController", function($scope, $http) {
    $scope.getUsers = function() {
        // i need to call getRoles method here
        $scope.getRoles() 
    }
});

      

in html

<manage-access get-roles="getRoles"></manage-access>

      

+2


source


You can use AngularJS / Factory service

I put the function getRoles

in a factory for the API, which can be injected anywhere.



Working demo

var RolesModule = angular.module('UserRoles', []);

RolesModule.factory('RolesAPI', function() {
    return {
        getRoles: function() {
            this.roles = 'my roles';
            console.log('test');
        }
    }
});

angular.module("test.controllers",['UserRoles'])
.controller("testController",function($scope,$rootScope,RolesAPI, $http) {
        $scope.getUsers = function() {
           RolesAPI.getRoles();
        }
});

angular.module('test.directives',['UserRoles'])
.directive("manageAccess", function() {
    return {
        restrict: "E",
        replace: true,
        templateUrl: "template/test.html",
        controller: function($scope, $element, $http) {                   

        }
    };
})

      

+3


source


If the function does not depend on directive elements, move it into the service by passing it to both the directive and the test controller.

+1


source







All Articles