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.
The directive scope uses prefixes to achieve that. Using prefixes helps establish a two-way or one-way binding between parent and directive scopes, and also make calls to parent scope methods. To access any data in the parent scope requires passing the data at two places – the directive scope and the directive tag.
AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
Restrict. Angular allows us to set a property named restrict on the object we return on our directive definition. We can pass through a string with certain letters letting Angular know how our directive can be used. function MyDirective() { return { restrict: 'E', template: '<div>Hello world!
Directive comes with many Directive Definition Objects (DDO). From them restrict is one. Using restrict option inside a Custom Directive we can prevent the access level of Directive for Element(E), Attribute(A), Comment(M) or Class(C).
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With