Angularjs 在何处将辅助函数置于角度';谁的指令?

Angularjs 在何处将辅助函数置于角度';谁的指令?,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我创建了一个简单的指令: angular.module("foo").directive('bar',function(){ return { ... template: '<div> \ <div ng-hide="param1.length == 0 && param2...">...</div> \ <in

我创建了一个简单的指令:

angular.module("foo").directive('bar',function(){
    return {
        ...
        template:
            '<div> \
                <div ng-hide="param1.length == 0 && param2...">...</div> \
                <input ng-show="param1.length == 0 && param2..." .../> \
             </div>',
        scope: {
            param1: '=',
            param2: '='
        }
    };
});
angular.module(“foo”).directive('bar',function(){
返回{
...
模板:
' \
... \
\
',
范围:{
参数1:“=”,
参数2:“=”
}
};
});
但是模板中有一个重复的复杂逻辑,所以我想将它提取到一个函数中,然后从模板中调用该函数。在哪里可以放置这样的函数,如何调用它?是否必须创建专用控制器?

在链接功能中:

return {
    ...,
    template: '<div><div ng-hide="foo()">...</div></div>',
    link: function(scope) {
        scope.foo = function() {
            return scope.param1.length == 0 && ...;
        };
    }
};
返回{
...,
模板:“…”,
链接:功能(范围){
scope.foo=函数(){
返回scope.param1.length==0&&。。。;
};
}
};

您可以使用declare服务在angular中实现这一点。从角度文档()

角度服务是连接在一起的可替换对象 使用依赖注入(DI)。您可以使用服务来组织和 在应用程序中共享代码


以下是我使用的一种简单、紧凑且易于理解的方法。
首先,在js中添加一个服务

app.factory('Helpers', [ function() {
      // Helper service body

        var o = {
        Helpers: []

        };

        // Dummy function with parameter being passed
        o.getFooBar = function(para) {

            var valueIneed = para + " " + "World!";

            return valueIneed;

          };

        // Other helper functions can be added here ...

        // And we return the helper object ...
        return o;

    }]);
然后,在控制器中,注入helper对象,并使用任何可用函数,如下所示:

app.controller('MainCtrl', [

'$scope',
'Helpers',

function($scope, Helpers){

    $scope.sayIt = Helpers.getFooBar("Hello");
    console.log($scope.sayIt);

}]);