functionality of angular directive before return and compile chain

一笑奈何 提交于 2019-12-13 04:23:20

问题


It is possible to run javascript in a directive before returning anything, as well as in a directive's compile step before returning anything:

    angular.module('foo').directive('fooDirective', [function(){
  console.debug('before return');
  return {
    restrict: 'E',
    controller: function($scope){
      console.debug('controller');
    },
    compile: function(scope, elem){
      console.debug('compile');
      return {
        pre: function(scope,elem, attr){
          console.debug('pre');
        },
        post: function(scope,elem,attr){
          console.debug('post');
        }
      }
    }
  }
}]);

  <body ng-app="foo">
    <foo-directive></foo-directive>
    <foo-directive></foo-directive>
  </body>

This produces the following console log order:

before return 
compile
compile 
controller
pre 
post 
controller 
pre 
post 

I have several questions about this:

1) Why would I ever want to run code before returning the actual directive object? What would be a usecase?

2) Why would I ever want to run code before returning the pre/post link functions? How is the prelink step different from the compile step? What is a use case?

3) Why does compile run twice in succession when there is two items, while everything else runs iteratively in the same order irrelevantly of number of elements?

Plunk: http://plnkr.co/edit/1JPYLcPlMerXlwr0GnND?p=preview


回答1:


  1. You would want to do this so you can have some private method definitions that only your object can use.

  2. You would want to do this if you were utilizing some service precompile to get the data for the directive, and post compile to use the data and do something with it.

  3. No idea

  4. I think there is some weird bubbling going on.

  5. because you only have two instances of your directive.

This is what I see in the console log:

before return 
compile 
compile
controller 
pre 
post 
controller 
pre 
post 


来源:https://stackoverflow.com/questions/22950663/functionality-of-angular-directive-before-return-and-compile-chain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!