从 AngularJS 中的指令添加指令
Add directives from directive in AngularJS
>我正在尝试构建一个指令,该指令负责向声明它的元素添加更多指令。例如,我想构建一个指令来负责添加 datepicker
、 datepicker-language
和 ng-required="true"
。
如果我尝试添加这些属性然后使用$compile
我显然会生成一个无限循环,所以我正在检查我是否已经添加了所需的属性:
angular.module('app')
.directive('superDirective', function ($compile, $injector) {
return {
restrict: 'A',
replace: true,
link: function compile(scope, element, attrs) {
if (element.attr('datepicker')) { // check
return;
}
element.attr('datepicker', 'someValue');
element.attr('datepicker-language', 'en');
// some more
$compile(element)(scope);
}
};
});
当然,如果我不$compile
元素,则会设置属性,但不会引导指令。
这种方法是正确的还是我做错了?有没有更好的方法来实现相同的行为?
UDPATE:鉴于$compile
是实现这一目标的唯一方法,有没有办法跳过第一个编译过程(元素可能包含多个子元素(?也许通过设置terminal:true
?
更新 2:我尝试将指令放入 select
元素中,正如预期的那样,编译运行了两次,这意味着预期的 option
数量是两倍。
在单个 DOM 元素上有多个指令并且它们的应用顺序很重要,您可以使用 priority
属性对它们的应用。数字越大,首先运行。如果未指定默认优先级,则默认优先级为 0。
编辑:讨论结束后,这是完整的工作解决方案。关键是删除属性:element.removeAttr("common-things");
,以及element.removeAttr("data-common-things");
(以防用户在 html 中指定data-common-things
(
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);
}
};
}
};
});
工作钻机可在以下位置获得: http://plnkr.co/edit/Q13bUt?p=preview
或:
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
和priority: 1000
(一个很大的数字(:
当 DOM 准备就绪时,angular 遍历 DOM 以识别所有注册的指令,并根据priority
这些指令是否在同一元素上逐个编译指令。我们将自定义指令的优先级设置为高数字,以确保它首先被编译,并且使用 terminal: true
,编译此指令后将跳过其他指令。
编译我们的自定义指令时,它将通过添加指令并删除自身来修改元素,并使用$compile服务编译所有指令(包括跳过的指令(。
如果我们不设置 terminal:true
和 priority: 1000
,有可能在我们的自定义指令之前编译一些指令。当我们的自定义指令使用 $compile 编译元素 => 再次编译已经编译的指令时。这将导致不可预测的行为,尤其是在我们的自定义指令之前编译的指令已经转换了 DOM 时。
有关优先级和终端的更多信息,请查看如何理解指令的"终端"?
同时修改模板的指令的一个示例是ng-repeat
(优先级 = 1000(,编译ng-repeat
时,ng-repeat
在应用其他指令之前复制模板元素。
感谢@Izhaki的评论,这里是对ngRepeat
源代码的引用:https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js
实际上,您只需一个简单的模板标签即可处理所有这些问题。有关示例,请参阅 http://jsfiddle.net/m4ve9/。请注意,我实际上不需要超级指令定义的编译或链接属性。
在编译过程中,Angular 会在编译之前拉入模板值,因此您可以在那里附加任何进一步的指令,Angular 将为您处理。
如果这是一个需要保留原始内部内容的超级指令,则可以使用transclude : true
,并将内部替换为<ng-transclude></ng-transclude>
希望有帮助,如果有什么不清楚的地方,请告诉我
亚历克斯
这是一个解决方案,它将需要动态添加的指令移动到视图中,并添加一些可选的(基本(条件逻辑。这样可以保持指令干净,没有硬编码逻辑。
该指令采用一个对象数组,每个对象都包含要添加的指令的名称和要传递给它的值(如果有的话(。
我一直在努力思考像这样的指令的用例,直到我认为添加一些仅基于某些条件添加指令的条件逻辑可能很有用(尽管下面的答案仍然是人为的(。我添加了一个可选的 if
属性,该属性应包含布尔值、表达式或函数(例如在您的控制器中定义(,以确定是否应添加指令。
我还使用 attrs.$attr.dynamicDirectives
来获取用于添加指令的确切属性声明(例如 data-dynamic-directive
, dynamic-directive
( 没有要检查的硬编码字符串值。
普伦克演示
angular.module('plunker', ['ui.bootstrap'])
.controller('DatepickerDemoCtrl', ['$scope',
function($scope) {
$scope.dt = function() {
return new Date();
};
$scope.selects = [1, 2, 3, 4];
$scope.el = 2;
// For use with our dynamic-directive
$scope.selectIsRequired = true;
$scope.addTooltip = function() {
return true;
};
}
])
.directive('dynamicDirectives', ['$compile',
function($compile) {
var addDirectiveToElement = function(scope, element, dir) {
var propName;
if (dir.if) {
propName = Object.keys(dir)[1];
var addDirective = scope.$eval(dir.if);
if (addDirective) {
element.attr(propName, dir[propName]);
}
} else { // No condition, just add directive
propName = Object.keys(dir)[0];
element.attr(propName, dir[propName]);
}
};
var linker = function(scope, element, attrs) {
var directives = scope.$eval(attrs.dynamicDirectives);
if (!directives || !angular.isArray(directives)) {
return $compile(element)(scope);
}
// Add all directives in the array
angular.forEach(directives, function(dir){
addDirectiveToElement(scope, element, dir);
});
// Remove attribute used to add this directive
element.removeAttr(attrs.$attr.dynamicDirectives);
// Compile element to run other directives
$compile(element)(scope);
};
return {
priority: 1001, // Run before other directives e.g. ng-repeat
terminal: true, // Stop other directives running
link: linker
};
}
]);
<!doctype html>
<html ng-app="plunker">
<head>
<script src="//code.angularjs.org/1.2.20/angular.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<div data-ng-controller="DatepickerDemoCtrl">
<select data-ng-options="s for s in selects" data-ng-model="el"
data-dynamic-directives="[
{ 'if' : 'selectIsRequired', 'ng-required' : '{{selectIsRequired}}' },
{ 'tooltip-placement' : 'bottom' },
{ 'if' : 'addTooltip()', 'tooltip' : '{{ dt() }}' }
]">
<option value=""></option>
</select>
</div>
</body>
</html>
我想添加我的解决方案,因为接受的解决方案对我不太有用。
我需要添加一个指令,但也要把我的指令放在元素上。
在此示例中,我向元素添加了一个简单的 ng 样式指令。为了防止无限编译循环并允许我保留我的指令,我在重新编译元素之前添加了一个检查以查看我添加的内容是否存在。
angular.module('some.directive', [])
.directive('someDirective', ['$compile',function($compile){
return {
priority: 1001,
controller: ['$scope', '$element', '$attrs', '$transclude' ,function($scope, $element, $attrs, $transclude) {
// controller code here
}],
compile: function(element, attributes){
var compile = false;
//check to see if the target directive was already added
if(!element.attr('ng-style')){
//add the target directive
element.attr('ng-style', "{'width':'200px'}");
compile = true;
}
return {
pre: function preLink(scope, iElement, iAttrs, controller) { },
post: function postLink(scope, iElement, iAttrs, controller) {
if(compile){
$compile(iElement)(scope);
}
}
};
}
};
}]);
尝试将状态存储在元素本身的属性中,例如superDirectiveStatus="true"
例如:
angular.module('app')
.directive('superDirective', function ($compile, $injector) {
return {
restrict: 'A',
replace: true,
link: function compile(scope, element, attrs) {
if (element.attr('datepicker')) { // check
return;
}
var status = element.attr('superDirectiveStatus');
if( status !== "true" ){
element.attr('datepicker', 'someValue');
element.attr('datepicker-language', 'en');
// some more
element.attr('superDirectiveStatus','true');
$compile(element)(scope);
}
}
};
});
我希望这对你有所帮助。
从 1.3.x 更改为 1.4.x。
在 Angular 1.3.x 中,这有效:
var dir: ng.IDirective = {
restrict: "A",
require: ["select", "ngModel"],
compile: compile,
};
function compile(tElement: ng.IAugmentedJQuery, tAttrs, transclude) {
tElement.append("<option value=''>--- Kein ---</option>");
return function postLink(scope: DirectiveScope, element: ng.IAugmentedJQuery, attributes: ng.IAttributes) {
attributes["ngOptions"] = "a.ID as a.Bezeichnung for a in akademischetitel";
scope.akademischetitel = AkademischerTitel.query();
}
}
现在在 Angular 1.4.x 中,我们必须这样做:
var dir: ng.IDirective = {
restrict: "A",
compile: compile,
terminal: true,
priority: 10,
};
function compile(tElement: ng.IAugmentedJQuery, tAttrs, transclude) {
tElement.append("<option value=''>--- Kein ---</option>");
tElement.removeAttr("tq-akademischer-titel-select");
tElement.attr("ng-options", "a.ID as a.Bezeichnung for a in akademischetitel");
return function postLink(scope: DirectiveScope, element: ng.IAugmentedJQuery, attributes: ng.IAttributes) {
$compile(element)(scope);
scope.akademischetitel = AkademischerTitel.query();
}
}
(来自公认的答案:https://stackoverflow.com/a/19228302/605586 来自庆都(。
在某些情况下可以工作的简单解决方案是创建并$compile包装器,然后将原始元素附加到其中。
像...
link: function(scope, elem, attr){
var wrapper = angular.element('<div tooltip></div>');
elem.before(wrapper);
$compile(wrapper)(scope);
wrapper.append(elem);
}
此解决方案的优点是,它通过不重新编译原始元素来保持简单。
如果添加的任何指令require
原始元素的任何指令,或者原始元素具有绝对定位,则这不起作用。
- 向动态生成的DOM添加Angular自定义指令
- 添加新联系人的指令
- IntroJS将指令添加到步骤标记
- AngularJs,在没有隔离的情况下将指令属性添加到作用域
- 如何将属性添加到自定义角度指令
- 如何将侦听器添加到 Angular 指令中
- 在页面上添加javascript后呈现指令
- 如何在元素之后将模板片段添加到angular.js中的指令中
- AngularJS:如何从指令添加的元素中删除事件处理程序
- 如何将多个指令添加到单个组件中
- 脚本从指令添加到 dom 不触发
- 向 angularjs 指令添加和编译属性
- 从 AngularJS 中的指令添加指令
- 如何在angular js中向多个ng include指令添加ng include回调
- Angular Js指令添加动态引导程序类
- 如何将项目列表从创建许多选择标记的指令添加到控制器范围
- Angularjs指令添加指令作为属性,并动态绑定它们
- 如何将nq-slider属性指令添加到Angular中含有ng-model的元素中
- AngularJs 工具提示指令 - 添加样式
- AngularJS - 如何向子指令添加功能