Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating private function inside directive

Tags:

angularjs

Is it possible to create a private function inside a directive? I need to do a rather complex process inside a directive to fill the directive's template.

Something like this (HTML):

<textarea the-result="data">
</textarea>

Javascript:

angular
.module("MyModule")
.directive("theResult", [function () {
    return {
        scope: {
            theResult: "="
            // calculatestuff = function(d){ // ... } can't put it here (error)
        },
        template: ' ... '
            + '{{calculatestuff(theResult.someproperties)}}'
            + ' ... '
    }
}])

Where can I put calculatestuff?

like image 415
Endy Tjahjono Avatar asked Jun 08 '13 08:06

Endy Tjahjono


1 Answers

Notice that directive(directiveName, directiveFunction) uses only what directiveFunction returns. You can do whatever you want inside this function, like, for instance, define other function :

angular
.module("MyModule")
.directive("theResult", [function () {
    var calculateStuff = function (d) {
        // ...
    };

    return {
        // ...
    }
}]);

But of course, calculateStuff won't exist anymore during the $digest cycles and is not link to the scope, so you won't be able to call it inside your template. If this is really what you want to do, contemplate to put your function in the scope, during the linking phase :

angular
.module("MyModule")
.directive("theResult", [function () {
    return {
        scope: {
            theResult: "="
        },
        template: ' ... '
            + '{{calculatestuff(theResult.someproperties)}}'
            + ' ... ',
        link : function ($scope) {
            $scope.calculateStuff = function (d) {
                // ...
            };
        }
    }
}]);

Since you use an isolated scope, this function won't be accesible from outside the directive.

like image 127
Blackhole Avatar answered Oct 18 '22 03:10

Blackhole