我对我正在做的事情有一个非常精简的版本,可以解决问题。
我有一个简单的 directive
。每当您单击一个元素时,它都会添加另一个元素。但是,它需要先编译才能正确呈现。
我的研究使我找到了$compile
。但是所有的例子都使用了一个复杂的结构,我真的不知道如何在这里应用。
小提琴在这里:http://jsfiddle.net/paulocoelho/fBjbP/1/
JS在这里:
var module = angular.module('testApp', [])
.directive('test', function () {
return {
restrict: 'E',
template: '<p>{{text}}</p>',
scope: {
text: '@text'
},
link:function(scope,element){
$( element ).click(function(){
// TODO: This does not do what it's supposed to :(
$(this).parent().append("<test text='n'></test>");
});
}
};
});
Josh David Miller 的解决方案:http://jsfiddle.net/paulocoelho/fBjbP/2/
你有很多毫无意义的 jQuery,但在这种情况下 $compile 服务实际上非常简单:
.directive( 'test', function ( $compile ) {
return {
restrict: 'E',
scope: { text: '@' },
template: '<p ng-click="add()">{{text}}</p>',
controller: function ( $scope, $element ) {
$scope.add = function () {
var el = $compile( "<test text='n'></test>" )( $scope );
$element.parent().append( el );
};
}
};
});
您会注意到我也重构了您的指令,以便遵循一些最佳实践。如果您对其中任何一个有疑问,请告诉我。
除了完善Riceball LEE添加新元素指令的例子
newElement = $compile("<div my-directive='n'></div>")($scope)
$element.parent().append(newElement)
可以使用以下方式向现有元素添加新的属性指令:
假设您希望将动态 my-directive
添加到 span
元素。
template: '<div>Hello <span>World</span></div>'
link: ($scope, $element, $attrs) ->
span = $element.find('span').clone()
span.attr('my-directive', 'my-directive')
span = $compile(span)($scope)
$element.find('span').replaceWith span
希望有帮助。
Maximum call stack size exceeded
错误总是由于无限递归而发生。我从未见过增加堆栈大小可以解决它的实例。
在 angularjs 上动态添加指令有两种风格:
将 angularjs 指令添加到另一个指令中
插入新元素(指令)
向元素插入新属性(指令)
插入新元素(指令)
这很简单。你可以在“链接”或“编译”中使用。
var newElement = $compile( "<div my-diretive='n'></div>" )( $scope );
$element.parent().append( newElement );
向元素插入新属性
这很难,两天之内就让我头疼。
使用“$compile”会引发严重的递归错误!!也许它应该在重新编译元素时忽略当前指令。
$element.$set("myDirective", "expression");
var newElement = $compile( $element )( $scope ); // critical recursive error.
var newElement = angular.copy(element); // the same error too.
$element.replaceWith( newElement );
所以,我必须找到一种方法来调用指令“链接”函数。很难获得隐藏在闭包内部的有用方法。
compile: (tElement, tAttrs, transclude) ->
links = []
myDirectiveLink = $injector.get('myDirective'+'Directive')[0] #this is the way
links.push myDirectiveLink
myAnotherDirectiveLink = ($scope, $element, attrs) ->
#....
links.push myAnotherDirectiveLink
return (scope, elm, attrs, ctrl) ->
for link in links
link(scope, elm, attrs, ctrl)
现在,它运作良好。
function addAttr(scope, el, attrName, attrValue) {
el.replaceWith($compile(el.clone().attr(attrName, attrValue))(scope));
}
如果您尝试动态添加使用内联 template
的指令,则 Josh David Miller 接受的答案非常有用。但是,如果您的指令利用 templateUrl
他的答案将不起作用。这对我有用:
.directive('helperModal', [, "$compile", "$timeout", function ($compile, $timeout) {
return {
restrict: 'E',
replace: true,
scope: {},
templateUrl: "app/views/modal.html",
link: function (scope, element, attrs) {
scope.modalTitle = attrs.modaltitle;
scope.modalContentDirective = attrs.modalcontentdirective;
},
controller: function ($scope, $element, $attrs) {
if ($attrs.modalcontentdirective != undefined && $attrs.modalcontentdirective != '') {
var el = $compile($attrs.modalcontentdirective)($scope);
$timeout(function () {
$scope.$digest();
$element.find('.modal-body').append(el);
}, 0);
}
}
}
}]);
乔什大卫米勒是正确的。
PCoelho,如果您想知道 $compile
在幕后做了什么以及如何从指令生成 HTML 输出,请看下面
$compile
服务编译包含指令(“test”作为元素)的 HTML ("< test text='n' >< / test >"
) 片段并生成一个函数。然后可以使用范围执行此函数以获取“来自指令的 HTML 输出”。
var compileFunction = $compile("< test text='n' > < / test >");
var HtmlOutputFromDirective = compileFunction($scope);
此处包含完整代码示例的更多详细信息:http://www.learn-angularjs-apps-projects.com/AngularJs/dynamically-add-directives-in-angularjs
受到许多先前答案的启发,我提出了以下“stroman”指令,它将用任何其他指令替换自身。
app.directive('stroman', function($compile) {
return {
link: function(scope, el, attrName) {
var newElem = angular.element('<div></div>');
// Copying all of the attributes
for (let prop in attrName.$attr) {
newElem.attr(prop, attrName[prop]);
}
el.replaceWith($compile(newElem)(scope)); // Replacing
}
};
});
重要提示:在 restrict: 'C'
中注册您要使用的指令。像这样:
app.directive('my-directive', function() {
return {
restrict: 'C',
template: 'Hi there',
};
});
你可以这样使用:
<stroman class="my-directive other-class" randomProperty="8"></stroman>
要得到这个:
<div class="my-directive other-class" randomProperty="8">Hi there</div>
Protip。如果您不想使用基于类的指令,那么您可以将 '<div></div>'
更改为您喜欢的内容。例如,有一个包含所需指令名称而不是 class
的固定属性。
不定期副业成功案例分享
$compile
的情况下完成此任务?顺便感谢您的回答!$compile
服务是将指令连接起来并将它们挂钩到事件循环中。在这种情况下$compile
没有办法,但在大多数情况下,像 ngRepeat 这样的另一个指令可以完成相同的工作(因此 ngRepeat 正在为我们进行编译)。您有特定的用例吗?