所以,这是我的问题。我有两个指令(例如父指令和子指令),并且我从父指令调用子指令,如下所示:
angular.module('components', [])
.directive('helloWorld', function() {
return {
restrict: 'E',
compile: function(element, attrs) {
var x = '<directive2></directive2>';
element.append(x);
}
}
})
.directive("directive2", function($compile, $parse) {
return {
restrict: 'E',
compile: function(iElement, iAttrs, transclude) {
iElement.append('<p>directive2</p>');
}
}
});
angular.module('HelloApp', ['components'])
这很好用。但现在我在编译的后置函数中编写一个条件,当该条件满足时,应该附加子指令。
我刚刚在 post 函数中添加了追加函数,但它不起作用。
angular.module('components', [])
.directive('helloWorld', function() {
return {
restrict: 'E',
compile: function(element, attrs) {
return {
post: function(scope, element, attrs) {
var x = '<directive2></directive2>';
element.append(x);
}
}
}
}
})
.directive("directive2", function($compile, $parse) {
return {
restrict: 'E',
compile: function(iElement, iAttrs, transclude) {
iElement.append('<p>directive2</p>');
}
}
});
angular.module('HelloApp', ['components'])
我不知道出了什么问题。 friend 们指导一下
最佳答案
在附加之前,您需要使用 $compile
服务,如下所示:
angular.module('components', [])
.directive('helloWorld', function($compile){
return {
restrict: 'E',
link: function(scope, element, attrs) {
var x = angular.element('<directive2></directive2>');
element.append($compile(x)(scope));
}
}
})
.directive("directive2", function() {
return {
restrict: 'E',
compile: function(element, attrs, transclude) {
element.append('<p>directive2</p>');
}
}
});
angular.module('HelloApp', ['components']);
关于javascript - 如何在编译后的函数中追加元素 - AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37118890/