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.
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 calledindex
.Now in your controller you can listen for events (such as a custom event you might title
removeCustom
) emitted by children using$scope.$on()
.Then in your custom directive you have to use
$scope.$emit()
to broadcast yourremoveCustom
event up the scope hierarchy to the controller.FYI: A directive can always remove itself by calling
$el.remove()
in the link function, but since your directive is created via angRepeat
it will just get recreated in the next digest. So you have to tell the controller to remove it from theinstances
array.according to New Dev in a previous comment, this is the way: