Dark star
Dark star

Reputation: 5852

Pass parameter from link function to the template in AngularJS 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

Upvotes: 1

Views: 2115

Answers (3)

Ashish Rajput
Ashish Rajput

Reputation: 1529

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";
    }
  }
});

EDIT

If you want to bind html use ngbindHtml

Please find the plnkr

Upvotes: 2

Anjul Garg
Anjul Garg

Reputation: 584

You can use 'this'

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

Upvotes: 0

khajaamin
khajaamin

Reputation: 876

there are multiple ways i need to explain you here so please consider both side changes need i mean you want to send variable from directive call

<html ng-app="app">
<body>
  <hello data-str="'I am don'"></hello>
</body>
</html>

here data-str means there str is variable which having text "I am don" thats it

now

angular.module("app", []);

angular.module("app").directive("hello", function() {
  return {
    scope:{
      str:"="
    },
    restrict: "E",
    template: '<div>{{linkVar}}{{str}}<div/>',
    link : function(scope, element, attrs) {
     scope.linkVar = 'It works!' 
      console.log(scope.str);
    }
  }
});

Here

you can see this in directive object added by me

 scope:{
          str:"="
        },  

here we decide that "str" will be provided when directive calls in html like this instead of only this Please take care

now

scope.linkVar = 'It works!' 

this is most important thing you should see scope.linkVar means you had just javascript variable with name str = "hello"; this is not angular way so angular will not update its all references. I mean when you use in templates.

now hope it clear and let me know if yes. Have a great time

khajaamin

Upvotes: 1

Related Questions