Dani Barca Casafont
Dani Barca Casafont

Reputation: 273

Attributes with templateUrl on Angularjs directive

I'm trying to create a templateUrl with dynamic content inside a directive, something like:

//index.html
...
<directive variable="Hi" />
...

//template.html
<div>{{ variable }}</div>

With a directive:

app.directive("directive",[
    function(){
        return {
            restrict: "E",
            replace: true,
            templateUrl: "template.html"
       }
    }
]);

In this example, what I would like to do is to replace {{ variable }} with "Hi", but I don't know how to. What would be the best way to achieve this?

Upvotes: 0

Views: 754

Answers (3)

snajahi
snajahi

Reputation: 910

Try this :

return {        
    restrict: "E",
    scope:{
        variable: '@',    //Note the '@'
    }
    replace: true,
    templateUrl: "template.html"
}
  • use the '@' character to indicate that you want to pass a value.
  • use the '=' character to indicate that you're passing a variable by reference.
  • use the '&' character to indicate that you're passing a function.

Upvotes: 2

cuttlas
cuttlas

Reputation: 981

or if you don't want an isolated scope, you can do this:

return {        
    restrict: "E",
    link: function(scope, elem ,attr) {
        scope.variable = attr.variable;
    },
    replace: true,
    templateUrl: "template.html"
}

Upvotes: 0

AlwaysALearner
AlwaysALearner

Reputation: 43947

return {        
    restrict: "E",
    scope:{
        variable: '=',
    }
    replace: true,
    templateUrl: "template.html"
}

Upvotes: 1

Related Questions