4

I have some code which is working to add and remove entries to and from arrays in my scope. Right now the code isn't reused but rather cut/pasted and tweaked. Also, it rather naughtily uses scope inheritance to access the array. I'm trying to create a directive that will fix these two problems. The directive works fine as long as I add entries to the array. As soon as I remove an entry I appear to break the bi-directional binding. Any clues as to how I should go about this?

Fiddle is here.

It shows the SkillsCtrl which is the old code, and ListEditCtrl which is the new (reproduced below from the fiddle). Adding an entry to either list will update both but removing an entry from either list breaks 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);
  };
}
3
  • where is your newitem object? Commented May 22, 2013 at 9:56
  • In the template for the directive. Commented May 22, 2013 at 10:06
  • Please, add directive to your question from Fiddle Commented May 22, 2013 at 10:08

1 Answer 1

4

It's because you use http://underscorejs.org/#without, which creates a copy of the array instead of just removing the item. When you remove an item a new array will be linked to the scope, and the new array is not linked with array in the isolate scope.

To solve this problem you can use splice instead, which removes the item 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/

Sign up to request clarification or add additional context in comments.

2 Comments

Some times I feel like underscore becomes the new jQuery. Libraries for mostly trivial tasks.
Yes, unfortunately IE8 doesn't have indexOf() in the Array prototype :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.