角度可重用功能

sup*_*her 2 angularjs

我有几个指令需要在完成它们之后调用相同的函数.此函数需要访问主控制器范围,还需要修改DOM.如何以及在何处声明此功能?

Umu*_*acı 7

您应该使用服务,服务可以访问$rootScope,虽然最好将DOM修改保持在指令级别,在某些情况下您可以使用它.

angular.module("myModule", [])
.factory("MyService", function ($rootScope) {
    return {
        myFunction: function () { // do stuff here }
    }
})
.directive("MyDirective", function (MyService) {
    return {
        link: function (scope, iElement, iAttrs) {
            // try do keep dom modification here, you have access to MyService,
            // let it do the algorithm and try to keep dom modification here.
            // PS: you can also inject $rootScope to directives.
        };
    };
});
Run Code Online (Sandbox Code Playgroud)