On the page there is an element with an attribute

some-attr="Hello Habr!" 

Its value is transmitted to the directive in two ways:

  1. through scope

  2. via attrs.someAttr

In the directive, these values ​​are also displayed in two ways:

  1. via template:

    "{{someAttr}} - {{qwerty}}",

  2. via console:

    console.log ('qwerty', qwerty); console.log ('someAttr', someAttr);

I don’t understand why in the first case qwerty is not displayed, and in the second case someAttr is not displayed. I was hoping that both qwerty and someAttr would be output in both cases.

Jsfiddle

    1 answer 1

    1. In qwerty template is not displayed, because a variable is not defined in scope; in the code below, it is defined in the link function and output.
    2. SomeAttr is not defined anywhere in the link function, so it swears with a reference error: someAttr is not defined

    I hope the comments in the code will clarify what is happening in the directive.

     angular.module('helloHabrahabr', []) .directive('habraHabr', function() { return { template:"{{some}}-{{qwerty}}", //тут выводятся значения из scope scope:{ some:'@someAttr' //тут передача значения some-attr в scope.some }, link: function (scope, element, attrs) { var qwerty = attrs.someAttr; //получение значения из some-attr //scope.some = attrs.someAttr; //можно закомментировать some:'@someAttr' в scope и раскомментировать это scope.qwerty = 10; //qwerty теперь равно 10 console.log('qwerty', qwerty); console.log('someAttr', someAttr);// someAttr is not defined он нигде не определен в этой функции link } } }); 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="helloHabrahabr"> <span habra-habr="hello" some-attr="Hello Habr!"></span> </div> 

    Also read the directives documentation.

    • Thanks, it became clearer. but still it is not clear why the second console.log doesn't output the variable from the scop: jsfiddle.net/4b4US/378 - cyklop77
    • one
      this function is triggered before the creation of the scope, add after console.log alert("test"); , and make sure (before pressing OK) that the data from the scope have not yet been drawn, and the function has been called. The documentation for the link function says: It is executed after the template has been cloned and is where directive logic will be put. - MrFylypenko
    • @MrFylypenko, not quite. The problem is precisely in the binding through @ . If you use for example = that value will already be available. And if you take one of the latest versions of the angular, and not 1.1 as an example - then everything will work as expected - Grundy