假设我有以下代码
- <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中删除被删除的实例?
希望是有道理的.
解决方法
@H_502_15@ 根据新Dev在 previous comment,这是方式:
- 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>