ssb
ssb

Reputation: 7502

How do I access an attribute's value in a directive?

I am trying to bind a model to an attribute in a directive.

Javascript --

function Main($scope) {
    $scope.text = "abc"
};

angular.module("myApp", [])
.directive("load", function ($compile) {
    return {
        restrict: 'E',
        replace: true,
        link: function (scope, element, attrs) {
           console.log(attrs);
           element.html(someFunction(attrs.text));
        }
    };
});

HTML --

<div ng-controller="Main">
    <load text="Hello {{text}}"></load>
</div>

You can find the jsFiddle here. In the fiddle I have done away with someFunction.

Upvotes: 0

Views: 115

Answers (2)

Sharondio
Sharondio

Reputation: 2614

Here is a quick plunk showing 5 different ways to get to scope from within a directive. The last one is the one you want: http://plnkr.co/edit/e2mMAq

Upvotes: 3

Ryan O&#39;Neill
Ryan O&#39;Neill

Reputation: 3757

Based on what I believe you are trying to do, you need to make two modifications:

  1. You have replace set to true, so you should probably add a template to your code to replace the element with your new markup.

  2. At the time that the linking phase occurs, the interpolation has not been evaluated yet, so you need to observe the attribute in order to look for changes.

      angular.module('myApp', [])
          .directive('load', function($compile) {
              return {
                  restrict: 'E',
                  replace: true,
                  link: function (scope, element, attrs) {
                      console.log(attrs);
                      element.html(attrs.text);
    
                      attrs.$observe('text', function(value) {
                          console.log('new value = ' + value);
                          element.html(value);
                      });
                  }
    
              };
          });
    

Take a look at the section observing interpolated attributes for more details.

Upvotes: 1

Related Questions