2

I'm using a directive to separate the logic for an entity (for example, a person).

So I have a people service that stores an array of people like:

this.people = ["Person 1", "Person 2", "etc"];

The controller then injects that service, and sends data to a template that contains my directive. So my template looks something like:

<div ng-repeat="person in people">
    <person name="person"></person>
</div>

Now, in my directive I have a delete function (called by clicking a button in the directive's template, which looks something like this (People service also injected into directive):

delete People.people[id];

The problem is, the rest of my directive's template remains intact. I want to remove the directive completely upon deletion. How is this possible? I've tried hiding it by using ng-hide and setting a 'deleted' property in the directive's scope to true upon deletion, but the empty (without data) directive template remains. I've looked into scope.$destroy(), element.remove(), etc, but nothing has worked and nothing seems really clear in the documentation...

How can I destroy/remove a directive completely from within itself (i.e. upon calling a delete function)?

Fiddle: http://jsfiddle.net/VSph2/107/

Click delete and the data is gone, but the directive (and template) remains, showing 'name:'. How can I remove the directive completely on delete?

Anonymous
  • 5,875
  • 7
  • 39
  • 68
  • `ng-repeat` controls what's rendered inside of it, deleting the item in the array of what it is iterating over and calling `scope.$apply()` should make `ng-repeat` delete the dom element. Can you show your directive or make a simplified JSFiddle of this? – Philipp Gayret Feb 10 '14 at 12:50
  • It says there's already an $apply() in progress... give me 5 mins and I'll make a quick fiddle. – Anonymous Feb 10 '14 at 12:55
  • 1
    @user1066946 - Fiddle example here: http://jsfiddle.net/VSph2/107/ (Click delete and the directive template remains.. I want to remove the directive completely) – Anonymous Feb 10 '14 at 13:23

1 Answers1

2

You are deleting object, but empty element in array remains, it is just null reference instead of pointing to an existing object.

Use

this.peopleIds.splice(this.peopleIds.indexOf(personId), 1);

to remove it from array, and that element will not be rendered in for loop anymore.

Reference: How do I remove a particular element from an array in JavaScript?

Community
  • 1
  • 1
Goran Obradovic
  • 8,771
  • 8
  • 47
  • 77
  • I just figured this out for myself literally as you posted it (added {{people}} and {{peopleIds}} to the template and saw that the array still contained two null values. Thanks! Wasted a lot of time on this. :( – Anonymous Feb 10 '14 at 13:36