How to remove from an array in angular directive

I have code that works on adding and removing entries to and from arrays in my area. At the moment, the code is not reused, but cut / pasted and configured. Also, it pretty naughtly uses area inheritance to access the array. I am trying to create a directive that will fix these two problems. The directive works fine while I add entries to the array. As soon as I delete the record, I seem to break the bi-directional binding. Any tips on how I should do this?

Fiddle is here .

It shows SkillsCtrl, which is old code, and ListEditCtrl, which is new (reproduced below from the fiddle). Adding an entry to any list will update both, but deleting an entry from one of these lists interrupts the binding.

function SkillsCtrl($scope) { $scope.addSkill = function () { $scope.profile.skills = $scope.profile.skills || []; $scope.profile.skills.push($scope.newskill); $scope.newskill = ""; }; $scope.removeSkill = function () { $scope.profile.skills = _.without($scope.profile.skills, this.skill); }; } function ListEditorCtrl($scope) { $scope.addItem = function () { $scope.list = $scope.list || []; $scope.list.push($scope.newitem); $scope.newitem = ""; }; $scope.removeItem = function () { $scope.list = _.without($scope.list, this.item); }; } 
+4
source share
1 answer

This is because you are using http://underscorejs.org/#without , which creates a copy of the array instead of just deleting the element. When you delete an item, the new array will be associated with the area, and the new array will not be associated with the array in the selection area.

To solve this problem, you can use splicing instead, which removes the element from the original array:

 $scope.removeSkill = function() { $scope.profile.skills.splice(_.indexOf($scope.profile.skills, this.skill),1); }; 

...

 $scope.removeItem = function() { $scope.list.splice(_.indexOf($scope.list, this.item),1); }; 

Updated plunker: http://jsfiddle.net/jtjf2/

+4
source

Source: https://habr.com/ru/post/1482121/


All Articles