Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear a public variable in Angular Service

I am fairly new to Angular and ran into an issue, google and stack overflow didn't turn up anything useful, I believe largely due to the fact I don't even know what to search for. So here's my problem hoping you could help me resolve. I have the following code: JSFiddle

HTML

<button ng-click="reload()">Reload</button>
<button ng-click="loadMore()">Load More</button>
<ul>
    <li ng-repeat="item in list">{{ item }}</li>
</ul>

JavaScript

var app = angular.module('app', []);

app.controller('mainCtrl', ['$scope', 'mainSvr', function ($scope, mainSvr) {
    $scope.list = mainSvr.list;
    $scope.reload = mainSvr.reload;
    $scope.loadMore = mainSvr.loadMore;
}]);

app.service('mainSvr', function () {
    // private
    var self = this;

    // public
    this.list = [];

    this.reload = function () {
        for (var i = 0; i < 5; i++) {
            self.list.push(i * 10);
        }
    };

    this.loadMore = function () {
        var listLength = self.list.length;
        for (var i = listLength; i < listLength + 5; i++) {
            self.list.push(i * 10);
        }
    }
});

When I click on reload I want to clear and re-populate the list (so it shows 0-40 again), how do I do it? I tried:

this.reload = function () {
    self.list = [];
    for (var i = 0; i < 5; i++) {
        self.list.push(i * 10);
    }
};

But it didn't work, nothing show up at all. I use debugger and break point and saw that the list is actually cleared and re-populated, somehow the UI doesn't pick it up when I do self.list = []; Please help me understand what I did wrong.

like image 765
MajorNerd Avatar asked Dec 09 '25 09:12

MajorNerd


1 Answers

You need to reset existing array instead of overwriting array reference with new one. You can do it for example like this:

this.reload = function () {
    self.list.length = 0;
    for (var i = 0; i < 5; i++) {
        self.list.push(i * 10);
    }
};

Angular uses strict object comparison in watchers digest cycle, so when you reset list with self.list = [] you completely overwrite object reference, so Angular doesn't know that you updated previous it used to render in the list. On the other hand, this.list.length = 0 is the quick way to clear array, not to overwrite with new one, but actually clear it.

Demo: https://jsfiddle.net/fz2zgozx/2/

like image 124
dfsq Avatar answered Dec 11 '25 23:12

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!