Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using attribute text value in AngularJS directive

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.

like image 754
C1pher Avatar asked Mar 19 '26 02:03

C1pher


2 Answers

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/

like image 159
Manny D Avatar answered Mar 22 '26 04:03

Manny D


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>',
    }
});
like image 23
jelinson Avatar answered Mar 22 '26 04:03

jelinson