javascript - Angular 指令 - 编译 Vs 链接 - 编译不只渲染一次

标签 javascript angularjs angularjs-directive

我有以下代码。我希望编译只运行一次,链接运行 5 次。

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js" ></script> 
    <style>.red{color:red;}.blue{background:blue;}</style>
</head>
<body ng-app="myApp" ng-controller="myCtrl"> 
<div hello dear> 1 </div>
<div hello dear> 2 </div>
<div hello dear> 3 </div>
<div hello dear> 4 </div>
<div hello dear> 5 </div>
<script>
//module declaration
var app = angular.module("myApp",[]);
//controller declaration
app.controller('myCtrl',function($scope){
    //no code
});
//directives declaration
app.directive('hello',function(){
    return{
        restrict: 'A',
        compile: function(tElement, tAttributes){
            tElement.addClass("red");
            console.log("compiled");
        },
    }
});
app.directive('dear',function(){
    return{
        restrict: 'A',
        link: function($scope, element, attributes){
            element.addClass("blue");
            console.log("linked");
        }
    }
});
</script> 
</body> 
</html>

期望:

编译运行一次。链接运行5次。

结果:

编译和链接都运行了 5 次。

屏幕截图:

enter image description here

引用:

http://www.bennadel.com/blog/2794-when-do-you-need-to-compile-a-directive-in-angularjs.htm

有人能告诉我为什么编译运行 5 次(或者,如何只运行一次)?

最佳答案

每个指令的编译阶段都在链接阶段之前,因为您应用了 hello 5 个元素上的指令编译然后链接 5 次是预期的行为。可以找到指令与子指令的链接过程的更详细说明 here .

编译函数

当 Angular 启动时,每个指令的编译函数只被调用一次。

正式来说,这是执行不涉及范围或数据绑定(bind)的(源)模板操作的地方。

主要是为了优化目的;考虑以下标记:

<tr ng-repeat="raw in raws">
    <my-raw></my-raw>
</tr>

<my-raw>指令将呈现一组特定的 DOM 标记。所以我们可以:

允许 ng-repeat 复制源模板(<my-raw>),然后修改每个实例模板的标记(在编译函数之外)。 修改源模板以包含所需的标记(在编译函数中),然后允许 ng-repeat 复制它。 如果 raws 集合中有 1000 个项目,后一种选择可能比前一种更快。

做:

  • 处理标记,使其用作实例(克隆)的模板。

不要:

  • 附加事件处理程序。
  • 检查子元素。
  • 设置对属性的观察。
  • 在示波器上设置 watch 。

关于javascript - Angular 指令 - 编译 Vs 链接 - 编译不只渲染一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36911286/

相关文章:

AngularJS Promises - 模拟 http promise

javascript - 如何从带参数的指令调用 Angular Controller 作用域函数?

javascript - 为什么 'onhashchange' in(window) 有效?

javascript - 如何将两个更新请求合并为一个?

javascript - Angular-Schema-Form 在 SCHEMA 更改时更改 FORM

javascript - 从属性指令中观察元素的 ngModel

javascript - 自定义表单验证器在 Angular 1.3 中因 $timeout 和 $setValidity 失败

javascript - Navigo.js 仅适用于本地主机

javascript - 如何将 jimp 对象转换为 Node 中的图像缓冲区?

带有 AJAX 数据源、排序和过滤的 Angularjs ng-table