Skip to content Skip to sidebar Skip to footer

Can A Directive Delete Itself From A Parent Scope

Let's say I have the following code
&

Solution 1:

according to New Dev in a previous comment, this is the way:

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}];
  });
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="app"><divng-repeat="i in instances"><custom-directivemodel="i"on-remove="instances.splice($index,1)"></custom-directive></div></div>

Solution 2:

First, don't use ngModel as a DOM attribute. This is an AngularJS directive used to bind form inputs to scope variables.

I've renamed it to model and added an extra attribute called index.

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

Now in your controller you can listen for events (such as a custom event you might title removeCustom) emitted by children using $scope.$on().

app.controller('controller',function($scope) {
    $scope.instances = [.....];
    $scope.$on('removeCustom',function($index) {
        delete $scope.instances[$index];
    });
});

Then in your custom directive you have to use $scope.$emit() to broadcast your removeCustom event up the scope hierarchy to the controller.

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);
        }
    });

FYI: A directive can always remove itself by calling $el.remove() in the link function, but since your directive is created via a ngRepeat it will just get recreated in the next digest. So you have to tell the controller to remove it from the instances array.

Post a Comment for "Can A Directive Delete Itself From A Parent Scope"