指令可以从父范围中删除自身吗

Can a directive delete itself from a parent scope

假设我有以下代码

<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?

中删除已删除的实例

希望这是有道理的。

首先,不要将 ngModel 用作 DOM 属性。这是一个 AngularJS 指令,用于将表单输入绑定到范围变量。

我已将其重命名为 model 并添加了一个名为 index 的额外属性。

<div ng-app="app" ng-controller="controller">
  <div ng-repeat="instance in instances>
    <customDirective model="instance" index="$index"></customDirective>
  </div>
</div>

现在,在您的控制器中,您可以使用 $scope.$on().

侦听 children 发出的事件(例如您可能标题为 removeCustom 的自定义事件)
app.controller('controller',function($scope) {
    $scope.instances = [.....];
    $scope.$on('removeCustom',function($index) {
        delete $scope.instances[$index];
    });
});

然后在您的自定义指令中,您必须使用 $scope.$emit() 将您的 removeCustom 事件 up 范围层次结构广播到控制器。

app.directive('customDirective', function($log) {
    return {
        restrict: 'E',
        templateUrl: './template.htm',
        scope: {
            model:"=",
            index:"="
        },
        link: function($scope,$el,$attr) {
            // when you need to remove this
            $scope.$emit('removeCustom',$scope.index);
        }
    });

仅供参考:指令始终可以通过在 link 函数中调用 $el.remove() 来删除 自身 ,但是由于您的指令是通过 ngRepeat 它将在下一个摘要中重新创建。所以你必须告诉控制器将它从 instances 数组中删除。

根据 中的 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>