Russell Durham
Russell Durham

Reputation: 624

Resolving scope variables in an angular directive

I'm working on creating an angular directive (element) that will apply some transformation to the text within.

Here is the directive:

module.directive('myDir', function() {
    return {
      restrict: 'E',
      link: function(scope, elem, attrs) {
        console.log(elem.text());       
      },
    };
  });

For now I've just placed a console.log in there to make sure I am seeing the expected text.

If my html is like this it works as expected:

<my-dir>Hello World!</my-dir>

However, if I use a variable from the scope such as this:

<my-dir>{{myMessage}}</my-dir>

Then that is the text I seen in the console output instead of the variables value. I think I understand why the output is this way, however I'm not sure how to get the correct value. The requirement is that the directive should be able to transform text from both examples.

Thoughts?

Upvotes: 0

Views: 47

Answers (4)

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

If you really interested get the interpolated content then do use $interpolate service to evaluated the interpolated content.

Code

link: function(scope, elem, attrs) {
    console.log($interpolate(elem.text())(scope));
},

Don't forget to add $interpolate as dependency on directive function.

Upvotes: 2

charlietfl
charlietfl

Reputation: 171669

I would suggest you use an isolated scope on directive which will give you access to the value without having to get it from the dom. You will also be able to manipulate it directly in the link function as part of scope

<my-dir my-message="myMessage"></my-dir>

JS

module.directive('myDir', function() {
    return {
      restrict: 'E',
      template: '{{myMessage}}',
      scope:{
        myMessage: '=', 
      },
      link: function(scope, elem, attrs) {
        console.log(scope.myMessage);       
      },
    };
}); 

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191986

Use $interpolate service to convert the string to a function, and apply the scope as parameter to get the value (fiddle):

module.directive('myDir', function($interpolate) {
    return {
      restrict: 'E',
      link: function(scope, elem, attrs) {
        console.log($interpolate(elem.text())(scope));
      },
    };
  });

Upvotes: 2

RWAM
RWAM

Reputation: 7018

Have a look on $compile or http://odetocode.com/blogs/scott/archive/2014/05/07/using-compile-in-angular.aspx

This should work:

module.directive('myDir', function($compile) {
  return {
    restrict: 'E',
    link: function(scope, elem, attrs) {
      console.log($compile(elem.text())(scope));       
    },
  };
});

Upvotes: 0

Related Questions