簡體   English   中英

從另一個控制器中的指令內部定義的一個控制器調用方法:AngularJS

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

我有一個指令,其中存在控制器,我有一個功能。 我需要從另一個控制器調用該函數。

指令:

    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>

如果函數不依賴於指令元素,則將其移動到服務將其傳遞給指令和testcontroller。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM