1

I am using ngRepeat for ul lists like below

<ul class="dropdown-menu dropdown-menu-right" role="menu" style="overflow:auto; max-height:180px;">
    <li ng-repeat="(k, v) in dataDict">
        <a href="" ng-click="$parent.dataField = k">{{v}}</a>
    </li>
</ul>

Javascript code works like this:

app.controller("myController", ["$scope", function ($scope) {
    $scope.dataField = "";
    $scope.dataDict= {};
    $scope.addElement = function (key, value) {
        $scope.dataDict[key] = value;
    }
    $scope.removeElement = function (key) {
        delete $scope.dataDict[key];
    }
}]);

When I add an element it works ok.

When I delete it is still visible for user but not avaliable form javascript. How to make delete work work?

I've found that for standart arrays you can do it like array.splice(index, 1); but for dictionary like object this is not possible.

3
  • did you try adding a $scope.$digest(); after the delete? Dec 10, 2014 at 14:26
  • I've tried it directly(throws that apply is in progress) and int setTimeout(nothing is thrown, but view is not changed)
    – EOG
    Dec 10, 2014 at 14:42
  • Could you provide a fiddle, so we can more easily edit your code? I don't see where you call removeElement or addElement Dec 10, 2014 at 14:43

2 Answers 2

0

It's difficult to say why this isn't working for you, but I'd guess that AngularJS uses some sort of caching mechanism which does not comply with calls to delete on an object bound with ng-repeat.

Here are some alternatives:

Option 1: Consider using a list rather than object. Your code would undergo very minor changes - instead of repeating key/values of an object, you'd iterate a list of object which would have a key field and a value field. Pretty straightforward. Instead of deleting, you'd just splice the list as you mentioned in your question.

Option 2: If you insist on staying with the key/value repeat method, consider replacing the object when calling removeElement with a new data dict which is equivalent to the previous one, minus the unwanted key - like so:

$scope.removeElement = function (key) {
  var newDataDict = {};
  for (var dataKey in $scope.dataDict) {
      if (key !== dataKey) {
          newDataDict[dataKey] = $scope.dataDict[dataKey];
      }
  }

  $scope.dataDict = newDataDict;
}
-1

Turned out I had a $watch added on that dictionary-like object in child controller that unintentionaly re-added record on delete. Everything in angular works as it should after fixing $watch code.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.