I have a very boiled down version of what I am doing that gets the problem across.
我有一个非常简化的版本,我正在做的是解决问题。
I have a simple directive
. Whenever you click an element, it adds another one. However, it needs to be compiled first in order to render it correctly.
我有一个简单的指令。每当您单击一个元素时,它会添加另一个元素。但是,需要首先编译它才能正确呈现它。
My research led me to $compile
. But all the examples use a complicated structure that I don't really know how to apply here.
我的研究让我得到了编译。但是所有的例子都使用了一个复杂的结构,我真的不知道如何在这里应用。
Fiddles are here: http://jsfiddle.net/paulocoelho/fBjbP/1/
小提琴在这里:http://jsfiddle.net/paulocoelho/fBjbP/1/
And the JS is here:
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>");
});
}
};
});
Solution by Josh David Miller: http://jsfiddle.net/paulocoelho/fBjbP/2/
Josh David Miller的解决方案:http://jsfiddle.net/paulocoelho/fBjbP/2/
7 个解决方案
#1
251
You have a lot of pointless jQuery in there, but the $compile service is actually super simple in this case:
你有很多毫无意义的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 );
};
}
};
});
You'll notice I refactored your directive too in order to follow some best practices. Let me know if you have questions about any of those.
您会注意到我也重构了您的指令,以便遵循一些最佳实践。如果您对这些问题有任何疑问,请与我们联系。
#2
72
In addition to perfect Riceball LEE's example of adding a new element-directive
除了完美的Riceball LEE添加新元素指令的例子
newElement = $compile("<div my-directive='n'></div>")($scope)
$element.parent().append(newElement)
Adding a new attribute-directive to existed element could be done using this way:
可以使用以下方式将新的attribute-directive添加到现有元素:
Let's say you wish to add on-the-fly my-directive
to the span
element.
假设您希望将on-the-fly 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
Hope that helps.
希望有所帮助。
#3
43
Dynamically adding directives on angularjs has two styles:
在angularjs上动态添加指令有两种样式:
Add an angularjs directive into another directive
- inserting a new element(directive)
- 插入新元素(指令)
- inserting a new attribute(directive) to element
- 向元素插入新属性(指令)
inserting a new element(directive)
it's simple. And u can use in "link" or "compile".
这很简单。你可以在“链接”或“编译”中使用。
var newElement = $compile( "<div my-diretive='n'></div>" )( $scope );
$element.parent().append( newElement );
inserting a new attribute to element
It's hard, and make me headache within two days.
这很难,两天之内让我头疼。
Using "$compile" will raise critical recursive error!! Maybe it should ignore the current directive when re-compiling element.
使用“$ 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 );
So, I have to find a way to call the directive "link" function. It's very hard to get the useful methods which are hidden deeply inside closures.
所以,我必须找到一种方法来调用指令“链接”功能。获取隐藏在闭包内的有用方法非常困难。
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)
Now, It's work well.
现在,它运作良好。
#4
9
function addAttr(scope, el, attrName, attrValue) {
el.replaceWith($compile(el.clone().attr(attrName, attrValue))(scope));
}
#5
5
The accepted answer by Josh David Miller works great if you are trying to dynamically add a directive that uses an inline template
. However if your directive takes advantage of templateUrl
his answer will not work. Here is what worked for me:
如果您尝试动态添加使用内联模板的指令,则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);
}
}
}
}]);
#6
5
Josh David Miller is correct.
Josh David Miller是对的。
PCoelho, In case you're wondering what $compile
does behind the scenes and how HTML output is generated from the directive, please take a look below
PCoelho,如果你想知道$ compile在幕后做什么以及如何从指令生成HTML输出,请看下面
The $compile
service compiles the fragment of HTML("< test text='n' >< / test >"
) that includes the directive("test" as an element) and produces a function. This function can then be executed with a scope to get the "HTML output from a directive".
$ compile服务编译包含指令(“test”作为元素)的HTML片段(“
var compileFunction = $compile("< test text='n' > < / test >");
var HtmlOutputFromDirective = compileFunction($scope);
More details with full code samples here: http://www.learn-angularjs-apps-projects.com/AngularJs/dynamically-add-directives-in-angularjs
有关完整代码示例的更多详细信息,请访问:http://www.learn-angularjs-apps-projects.com/AngularJs/dynamically-add-directives-in-angularjs
#7
4
Inspired from many of the previous answers I have came up with the following "stroman" directive that will replace itself with any other directives.
受到许多先前答案的启发,我提出了以下“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
}
};
});
Important: Register the directives that you want to use with restrict: 'C'
. Like this:
重要说明:使用restrict注册要使用的指令:'C'。喜欢这个:
app.directive('my-directive', function() {
return {
restrict: 'C',
template: 'Hi there',
};
});
You can use like this:
你可以像这样使用:
<stroman class="my-directive other-class" randomProperty="8"></stroman>
To get this:
要得到这个:
<div class="my-directive other-class" randomProperty="8">Hi there</div>
Protip. If you don't want to use directives based on classes then you can change '<div></div>'
to something what you like. E.g. have a fixed attribute that contains the name of the desired directive instead of class
.
专家提示。如果您不想使用基于类的指令,那么您可以将“
#1
251
You have a lot of pointless jQuery in there, but the $compile service is actually super simple in this case:
你有很多毫无意义的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 );
};
}
};
});
You'll notice I refactored your directive too in order to follow some best practices. Let me know if you have questions about any of those.
您会注意到我也重构了您的指令,以便遵循一些最佳实践。如果您对这些问题有任何疑问,请与我们联系。
#2
72
In addition to perfect Riceball LEE's example of adding a new element-directive
除了完美的Riceball LEE添加新元素指令的例子
newElement = $compile("<div my-directive='n'></div>")($scope)
$element.parent().append(newElement)
Adding a new attribute-directive to existed element could be done using this way:
可以使用以下方式将新的attribute-directive添加到现有元素:
Let's say you wish to add on-the-fly my-directive
to the span
element.
假设您希望将on-the-fly 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
Hope that helps.
希望有所帮助。
#3
43
Dynamically adding directives on angularjs has two styles:
在angularjs上动态添加指令有两种样式:
Add an angularjs directive into another directive
- inserting a new element(directive)
- 插入新元素(指令)
- inserting a new attribute(directive) to element
- 向元素插入新属性(指令)
inserting a new element(directive)
it's simple. And u can use in "link" or "compile".
这很简单。你可以在“链接”或“编译”中使用。
var newElement = $compile( "<div my-diretive='n'></div>" )( $scope );
$element.parent().append( newElement );
inserting a new attribute to element
It's hard, and make me headache within two days.
这很难,两天之内让我头疼。
Using "$compile" will raise critical recursive error!! Maybe it should ignore the current directive when re-compiling element.
使用“$ 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 );
So, I have to find a way to call the directive "link" function. It's very hard to get the useful methods which are hidden deeply inside closures.
所以,我必须找到一种方法来调用指令“链接”功能。获取隐藏在闭包内的有用方法非常困难。
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)
Now, It's work well.
现在,它运作良好。
#4
9
function addAttr(scope, el, attrName, attrValue) {
el.replaceWith($compile(el.clone().attr(attrName, attrValue))(scope));
}
#5
5
The accepted answer by Josh David Miller works great if you are trying to dynamically add a directive that uses an inline template
. However if your directive takes advantage of templateUrl
his answer will not work. Here is what worked for me:
如果您尝试动态添加使用内联模板的指令,则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);
}
}
}
}]);
#6
5
Josh David Miller is correct.
Josh David Miller是对的。
PCoelho, In case you're wondering what $compile
does behind the scenes and how HTML output is generated from the directive, please take a look below
PCoelho,如果你想知道$ compile在幕后做什么以及如何从指令生成HTML输出,请看下面
The $compile
service compiles the fragment of HTML("< test text='n' >< / test >"
) that includes the directive("test" as an element) and produces a function. This function can then be executed with a scope to get the "HTML output from a directive".
$ compile服务编译包含指令(“test”作为元素)的HTML片段(“
var compileFunction = $compile("< test text='n' > < / test >");
var HtmlOutputFromDirective = compileFunction($scope);
More details with full code samples here: http://www.learn-angularjs-apps-projects.com/AngularJs/dynamically-add-directives-in-angularjs
有关完整代码示例的更多详细信息,请访问:http://www.learn-angularjs-apps-projects.com/AngularJs/dynamically-add-directives-in-angularjs
#7
4
Inspired from many of the previous answers I have came up with the following "stroman" directive that will replace itself with any other directives.
受到许多先前答案的启发,我提出了以下“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
}
};
});
Important: Register the directives that you want to use with restrict: 'C'
. Like this:
重要说明:使用restrict注册要使用的指令:'C'。喜欢这个:
app.directive('my-directive', function() {
return {
restrict: 'C',
template: 'Hi there',
};
});
You can use like this:
你可以像这样使用:
<stroman class="my-directive other-class" randomProperty="8"></stroman>
To get this:
要得到这个:
<div class="my-directive other-class" randomProperty="8">Hi there</div>
Protip. If you don't want to use directives based on classes then you can change '<div></div>'
to something what you like. E.g. have a fixed attribute that contains the name of the desired directive instead of class
.
专家提示。如果您不想使用基于类的指令,那么您可以将“