Using a YouTube tutorial created by John Lindquist, I was able to create a directive using a template. See fiddle: http://jsfiddle.net/37PSs/
Now, I want to use the value of the attribute as a variable to a function call. Something like this:
html:
<hello-world name="World"></hello-world>
javascript - directive:
template: '<span>myFunction({{name}})</span>'
javascript - myFunction(theirName):
return ("Hello, " + String(theirName) + "!");
The closest I've been able to get is passing an [object Window] to my function.
You need to wrap your function call in {{}} like so:
var myApp = angular.module('myApp',[]);
myApp.directive('helloWorld', function() {
return {
restrict: 'E',
scope: {
name: '@'
},
controller: function ($scope) {
$scope.myFunc = function (input) {
return "Hello there, " + input + "!";
}
},
template: '<span>{{myFunc(name)}}</span>',
}
});
Updated fiddle: http://jsfiddle.net/bh2KY/
Given the nature of your function, the AngularJS way to do this is with a custom filter, since you are just formatting a scope variable. A filter takes in input and modifies it into something presentable; filters can be reused often more easily than a function in a directive's controller scope.
I've created a JSFiddle, built off of the one created by Manny D's, that demonstrates how to do this. Admittedly, for this particular example, the directive then becomes overkill.
Here is the javascript from my example. Note that I am using different modules for the directive and filter, as is good practice.
'use strict';
var myApp = angular.module('myApp',['myFilters', 'myDirectives']);
angular.module('myFilters', []).filter('my_name', function() {
return function(name) {
return "Hello there, " + name + "!";
};
});
angular.module('myDirectives', []).directive('helloWorld', function() {
return {
restrict: 'E',
scope: {
name: '@'
},
template: '<span>{{name|my_name}}</span>',
}
});
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