Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put a helper function in angular's directive?

I created a simple directive:

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

but there is a duplicated complex logic inside the template so i would like to extract it to a function and just call that function from a template. Where can I put such function and how can I invoke it? Do I have to create a dedicated controller?

like image 310
piotrek Avatar asked Sep 18 '14 15:09

piotrek


1 Answers

In the link function:

return {
    ...,
    template: '<div><div ng-hide="foo()">...</div></div>',
    link: function(scope) {
        scope.foo = function() {
            return scope.param1.length == 0 && ...;
        };
    }
};
like image 179
JB Nizet Avatar answered Oct 05 '22 03:10

JB Nizet