栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从AngularJS中的指令添加指令

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从AngularJS中的指令添加指令

如果在单个DOM元素上具有多个指令,并且它们的应用顺序很重要,则可以使用该

priority
属性对应用程序进行排序。较高的数字优先。如果未指定,则默认优先级为0。

编辑 :讨论之后,这是完整的工作解决方案。关键是 删除属性

element.removeAttr("common-things");
,以及
element.removeAttr("data-common-things");
(如果用户
data-common-things
在html中指定)

angular.module('app')  .directive('commonThings', function ($compile) {    return {      restrict: 'A',      replace: false,       terminal: true, //this setting is important, see explanation below      priority: 1000, //this setting is important, see explanation below      compile: function compile(element, attrs) {        element.attr('tooltip', '{{dt()}}');        element.attr('tooltip-placement', 'bottom');        element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop        element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html        return {          pre: function prelink(scope, iElement, iAttrs, controller) {  },          post: function postlink(scope, iElement, iAttrs, controller) {   $compile(iElement)(scope);          }        };      }    };  });

要么:

angular.module('app')  .directive('commonThings', function ($compile) {    return {      restrict: 'A',      replace: false,      terminal: true,      priority: 1000,      link: function link(scope,element, attrs) {        element.attr('tooltip', '{{dt()}}');        element.attr('tooltip-placement', 'bottom');        element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop        element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html        $compile(element)(scope);      }    };  });

解释为什么我们必须设置

terminal: true
and
priority: 1000
(一个大数字):

当DOM准备就绪时,angular遍历DOM以标识所有已注册的指令,并根据

priority
这些指令是否在同一元素
上来逐一编译指令。我们设定的自定义指令的优先级为较高的数字,以确保它会被编译 首先 ,用
terminal: true
,其他指令将被 跳过
该指令被编译后。

编译我们的自定义指令时,它将通过添加指令并删除自身来修改元素,并使用$ compile服务 编译所有指令(包括已跳过的指令)

如果我们没有设置

terminal:true
and
priority: 1000
,则有可能 自定义指令 之前先
编译一些指令。当我们的自定义指令使用$ compile编译element
=>时,再次编译已经编译的指令。这将导致无法预测的行为,尤其是如果在我们的自定义指令之前编译的指令已经转换了DOM。

也修改模板的指令的示例是

ng-repeat
(priority = 1000),在
ng-repeat
编译时,
ng-repeat

在应用其他指令之前先制作模板元素的副本



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/400550.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号