角度指令在返回和编译链之前的功能 [英] functionality of angular directive before return and compile chain

查看:20
本文介绍了角度指令在返回和编译链之前的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在返回任何内容之前在指令中运行 javascript,也可以在返回任何内容之前在指令的编译步骤中运行:

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 

我对此有几个问题:

1) 为什么我要在返回实际指令对象之前运行代码?什么是用例?

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

2) 为什么我要在返回前/后链接函数之前运行代码?预链接步骤与编译步骤有何不同?什么是用例?

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) 为什么当有两个项目时 compile 会连续运行两次,而其他一切都以与元素数量无关的相同顺序迭代运行?

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.

如果您使用某些服务预编译来获取指令的数据,然后编译后使用数据并对其进行处理,那么您会想要这样做.

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.

不知道

我认为正在发生一些奇怪的冒泡.

I think there is some weird bubbling going on.

因为你的指令只有两个实例.

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 

这篇关于角度指令在返回和编译链之前的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆