0

From what I understand it only runs once before the page is rendered. But is there ever a case where it runs after the page has been rendered?

I tried testing a few things with this plnkr:

angular
  .module('app', [])
  .directive('test', function($http) {
    return {
      restrict: 'E',
      template: '<input />',
      link: function(scope, el, attrs) {
        var input = angular.element(el[0].children[0]);
        input.on('change', function() {
          console.log('change event');
          scope.$apply(function() {
            console.log('digest cycle');
          });
        });
        input.on('keyup', function() {
          console.log('keyup event');
          var root = 'http://jsonplaceholder.typicode.com';
          $http.get(root+'/users')
            .success(function() {
              console.log('http request successful');
            })
            .error(function() {
              console.log('http request error');
            });
        });
        console.log('link function run');
      }
    };
  });
  1. Does typing in the input field cause the link function to run?
  2. Do event listeners cause the link function to run?
  3. Do http requests (made with $http?) cause the link function to run?
  4. Do digest cycles cause the link function to run?

The answer to all of these questions seem to be "no".

Adam Zerner
  • 17,797
  • 15
  • 90
  • 156
  • "And it's the linking function that executes once for each instantiation of the template." - [Misko Hevery](https://youtu.be/WqmeI5fZcho?t=16m41s). – Adam Zerner Jul 22 '15 at 15:38

2 Answers2

2

The link function runs when an instance of the directive is compiled, in this case, when a <test></test> element is created. That can be when angular's bootstrapping compiles the page, when it comes into being from a ng-if, when a ng-repeat makes it, when it's made with $compile, etc.

link will never fire twice for the same instance of the directive. Notably, it fires right after the template has been compiled in the directive's lifecycle.

Dylan Watt
  • 3,357
  • 12
  • 16
2

1 - No, it causes to change the only ng-model if you have it binded.

2 - No, it will only launch the code inside the event binds.

3 - Again no, the event bind will launch the $http.get(). And please don't put an $http directly on your directive. Use a factory or something like that.

4 - Dunno

As Dylan Watt said, the directive link runs only when the directive is compiled (only once) per element/attr.... You can compile it in different ways. Plain http, $compile, ng-repeat....

You can create a $watch inside your directive to "relaunch" some code on a binded element change.

This maybe can help you: How to call a method defined in an AngularJS directive?

Community
  • 1
  • 1
nada
  • 972
  • 5
  • 22