piotrek piotrek - 1 month ago 5
AngularJS Question

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?

Answer

In the link function:

return {
    ...,
    template: '<div><div ng-hide="foo()">...</div></div>',
    link: function(scope) {
        scope.foo = function() {
            return scope.param1.length == 0 && ...;
        };
    }
};