AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

后端 未结 5 2031
走了就别回头了
走了就别回头了 2020-11-27 12:42

I have two controllers and share data between them with an app.factory function.

The first controller adds a widget in the model array (pluginsDisplayed) when a link

相关标签:
5条回答
  • 2020-11-27 13:18

    I had the same issue. The problem was because 'ng-controller' was defined twice (in routing and also in the HTML).

    0 讨论(0)
  • 2020-11-27 13:23

    If you add a $scope.$apply(); right after $scope.pluginsDisplayed.splice(index,1); then it works.

    I am not sure why this is happening, but basically when AngularJS doesn't know that the $scope has changed, it requires to call $apply manually. I am also new to AngularJS so cannot explain this better. I need too look more into it.

    I found this awesome article that explains it quite properly. Note: I think it might be better to use ng-click (docs) rather than binding to "mousedown". I wrote a simple app here (http://avinash.me/losh, source http://github.com/hardfire/losh) based on AngularJS. It is not very clean, but it might be of help.

    0 讨论(0)
  • 2020-11-27 13:27

    Whenever you do some form of operation outside of AngularJS, such as doing an Ajax call with jQuery, or binding an event to an element like you have here you need to let AngularJS know to update itself. Here is the code change you need to do:

    app.directive("remove", function () {
        return function (scope, element, attrs) {
            element.bind ("mousedown", function () {
                scope.remove(element);
                scope.$apply();
            })
        };
    
    });
    
    app.directive("resize", function () {
        return function (scope, element, attrs) {
            element.bind ("mousedown", function () {
                scope.resize(element);
                scope.$apply();
            })
        };
    });
    

    Here is the documentation on it: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply

    0 讨论(0)
  • 2020-11-27 13:30

    There's an easy way to do that. Very easy. Since I noticed that

    $scope.yourModel = [];
    

    removes all $scope.yourModel array list you can do like this

    function deleteAnObjectByKey(objects, key) {
        var clonedObjects = Object.assign({}, objects);
    
         for (var x in clonedObjects)
            if (clonedObjects.hasOwnProperty(x))
                 if (clonedObjects[x].id == key)
                     delete clonedObjects[x];
    
        $scope.yourModel = clonedObjects;
    }
    

    The $scope.yourModel will be updated with the clonedObjects.

    Hope that helps.

    0 讨论(0)
  • 2020-11-27 13:36

    Remove "track by index" from the ng-repeat and it would refresh the DOM

    0 讨论(0)
提交回复
热议问题