我们说我有一个&#34; filterList&#34;元件。 Inside是<filter-item>
角度指令的列表。我希望每个<filter-item>
都有一个&#34;删除&#34;里面的按钮。单击删除按钮将从DOM中删除<filter-item>
。
我该怎么做?
<div class="filterList">
<filter-item></filter-item>
<filter-item></filter-item>
<filter-item></filter-item>
</div>
FilterItem指令:
myApp.directive('filterItem', ['$http', function($http){
return {
scope: { },
replace: true,
link: function(scope, element, attrs){
scope.remove = function() {
// Hmm, I sure do wonder what goes here Mr Jones.
}
},
template: '<div>Hi mom! <button on-click="remove()">Remove</button></div>'
}
});
答案 0 :(得分:0)
在link
内,你可以element.remove();
。
由于AngularJS具有jqLite,remove()
从DOM中删除指令的元素。如果您的指令不与任何模型绑定,则可以接受。当指令作为模型的结果呈现时,要小心操纵DOM,因为您没有更改模型,最终会产生奇怪的效果(例如重新渲染)。
(自我回答,但发现不在StackOverflow上的好帖子)
myApp.directive('filterItem', ['$http', function($http){
return {
scope: { },
replace: true,
link: function(scope, element, attrs){
scope.remove = function() {
element.remove();
}
},
template: '<div>Hi mom! <button on-click="remove()">Remove</button></div>'
}
});
答案 1 :(得分:0)
方法1:我不知道这是否是正确的方法,但您可以使用
<div class="filterList">
<filter-item></filter-item>
<filter-item></filter-item>
<filter-item></filter-item>
</div>
FilterItem directive:
myApp.directive('filterItem', ['$http', function($http){
return {
scope: {
hideDir:'=?'
},
replace: true,
link: function(scope, element, attrs){
scope.remove = function() {
// Hmm, I sure do wonder what goes here Mr Jones.
element.innerHTML='';
}
},
template: '<div>Hi mom! <button on-click="remove()">Remove</button></div>'
}
});
方法2:您也可以尝试在指令
中使用ng-if和change变量<div class="filterList" ng-if="!hideDir" hide-dir="hideDir">
<filter-item></filter-item>
<filter-item></filter-item>
<filter-item></filter-item>
</div>
FilterItem directive:
myApp.directive('filterItem', ['$http', function($http){
return {
scope: {
hideDir:'=?'
},
replace: true,
link: function(scope, element, attrs){
scope.remove = function() {
// Hmm, I sure do wonder what goes here Mr Jones.
scope.hideDir=true;
}
},
template: '<div>Hi mom! <button on-click="remove()">Remove</button></div>'
}
});