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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With