假设我有以下代码
<div ng-app="app" ng-controller="controller">
<div ng-repeat="instance in instances>
<customDirective ng-model="instance"></customDirective>
</div>
</div>
我的自定义指令有一个独立的范围,定义为:
app.directive('customDirective', function($log) {
return {
restrict: 'E',
templateUrl: './template.htm',
scope: {_instance:"=ngModel"},
link: function($scope) {
....
}
});
在这个指令中,我必须选择删除它。我的问题是如何与父作用域中的数组实例通信并告诉它销毁该对象并从我的 DOM 中删除已删除的实例?
希望这是有道理的。
最佳答案
根据 previous comment 中的 New Dev ,这是这样的:
var app = angular.module('app', [])
.directive('customDirective', function($log) {
return {
restrict: 'EA',
template: '<a href="" ng-click="onRemove()">remove me {{model.n}}</a>',
scope: {
model:"=",
onRemove:"&"
}
}
})
.run(function($rootScope) {
$rootScope.instances = [{n:1},{n:2},{n:3},{n:4}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-repeat="i in instances">
<custom-directive model="i" on-remove="instances.splice($index,1)">
</custom-directive>
</div>
</div>
关于javascript - 指令可以从父范围中删除自身吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27934426/