Can a directive delete itself from a parent scope

Matt picture Matt · Jan 14, 2015 · Viewed 10.3k times · Source

Let's say I have the following code

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

And my custom directive has an isolated scope, defined as:

 app.directive('customDirective', function($log) {
        return {
            restrict: 'E',
            templateUrl: './template.htm',
            scope: {_instance:"=ngModel"},
            link: function($scope) {
            ....
            }
        });

In this directive, I have to option to delete it. My question is how can I communicate back to the array instances in the parent scope and tell it to destroy this object and in effect remove the deleted instance from my DOM?

Hope that makes sense.

Answer

Lautaro Cozzani picture Lautaro Cozzani · Jan 14, 2015

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