Sajad Abedi Sajad Abedi - 5 months ago 23
AngularJS Question

Pass parameter from link function to the template in angular directive

I have simple directive and I want access to the variable in link function in the template. how i can achieve that?

My directive :

app.directive("hello", function() {
return {
restrict: "E",
template: '<div> '+str+' <div/>'
link : function(scope, element, attrs) {
var str = "hello";
}
}
});


Here is a code on codepen: demo

Answer

add the variable in the scope and they will be available in the template

scope.str = "hello";

and your template should use the angular expression

template: '<div>{{str}}<div/>',

so your directive will be like

app.directive("hello", function() {
  return {
    restrict: "E",
    template: '<div>{{str}}<div/>',
    link : function(scope, element, attrs) {
      scope.str = "hello";
    }
  }
});

Please find the plnkr

Comments