user1027620 user1027620 - 1 month ago 18
AngularJS Question

AngularJS Updating Scope from Service model

I have this in my controller

$scope.activities = Activities.getAll();

$httpService.getActivities().then(function (response) {
var activities = response.data.body;
Activities.addMany(activities);
});


Now my service looks something like this:

var _activities = [];

function addMany(activities) {
if (activities instanceof Array) {
_activities = _activities.concat(activities);
}
}


and:

function getAll() {
return _activities;
}


The view does not update after getActivities resolves. I checked and the response does in fact contain new activities and they are added to the _activities array in the service.

What could be the problem and how can I make sure that the scope always changes based on the service values?

Thanks in advance.

Answer

According to the docs (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) Javascript Array.concat method creates a new array.

This means that the _activities array returned from getAll function and resulting _activities array after addMany call are not the same array.

What you need to do is add elements to existing array not creating a new one. Instead of this:

_activities = _activities.concat(activities);

You should do it like this

for (var i=0; i < activities.length; i++) {
    _activities.push(activities[i]);
}