我想定义一个指令,它将首先显示第一个包含按钮的子项。如果我们单击该按钮,第二个子级将取代第一个。
HTML:
<div show-more>
<div>short <button ng-click="showMore()">click-me to show more</button></div>
<div>full</div>
</div>
Angular :
angular.module("app", [])
.directive("showMore", function() {
return {
restrict: 'A',
scope: {},
link: function(scope, element, attrs) {
var children = element.children();
var short = children[0];
var full = children[1];
element.empty().append(short);
scope.showMore = function() {
element.empty().append(full);
};
}
};
});
问题是,当我单击按钮时,没有任何反应。我尝试了很多,但还是不行。
您可以在此处观看现场演示:http://jsbin.com/rugov/2/edit
如何解决?
最佳答案
由于您要更改指令的 element
的 DOM,因此您需要重新 $compile
元素,如下所示:
.directive("showMore", function($compile) {
return {
restrict: 'A',
scope: {},
link: function(scope, element, attrs) {
var children = element.children();
var short = children[0];
var full = children[1];
element.empty().append(short);
$compile(element.contents())(scope);
scope.showMore = function() {
element.empty().append(full);
};
}
};
});
Working Example
关于javascript - 如何定义一个包含方法并可以由 `ng-click` 调用的 Angular Directive(指令)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26043620/