从另一个控制器中的指令内部定义的一个控制器调用方法:AngularJS

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

本文关键字:控制器 一个 调用 方法 AngularJS 另一个 指令 内部 定义      更新时间:2023-09-26

我有一个指令,其中存在控制器,其中有一个函数。我需要从另一个控制器调用该函数。

指令:

    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方法是我需要从不同控制器调用的方法。

控制器:

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

我该怎么做?

请帮忙,谢谢

您可以使用AngularJS服务/工厂

我把getRoles函数放在API的工厂中,它可以在任何地方注入。

工作演示

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) {                   
        }
    };
})

尝试以下

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');
                };
            }
        };
    });

控制器

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

在html 中

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

如果函数不依赖于指令元素,则将其移动到服务,并将其传递给指令和测试控制器。