Skip to content Skip to sidebar Skip to footer

AngularJS Updates Variable In A Different File Without Being Instructed To Do So

This is my JS on home.js: angular.module('HomeApp', ['BaseApp']) .controller('MainCtrl', ['$http', '$window', 'BaseService', function($http, $window, BaseService) { va

Solution 1:

Basically because self is different in each case.

Why it doesn't seem to propagate?

On the home.js, self is the controller's instance which is what the view has access to.

On base.js, self is the factory's instance so it's not the controller itself.

But why doesn't the same happen on like?

The reason the same doesn't apply on like, is cause when fetch the posts on your factory, you store a reference on the Factory (self.posts) and you return that same reference to the controller via Promise:

$http.get('/postsY/')
.then(function(response) {
   self.posts = response.data;
   callback(self.posts);
}, function(response) {
   self.obj.accessErrors(response.data, function(cerrorMessages) {
       callback(self.posts, cerrorMessages);
   });
});

Hence, effectively both references are the same. When you change the post on the like function on the factory, you reference to self.posts again and since both have the same references, the update appears to be propagated but in fact, you're using a single object being referenced in two places.

You can test this by changing self.posts on your factory to something else, such as self.foo and returning it the same way you're doing it.

Since you're returning self.obj on the Factory, you don't have access to the posts since the bare structure is like this:

self = {
  posts: [], // all your posts
  obj: {} // all your methods
}

You could attach posts to obj (or flatten the whole object into a single level) and return it and you could do this on your controller:

self.getPosts = function () {
  return BaseService.posts;
};

In that way you don't need to store anything in your controller.


Post a Comment for "AngularJS Updates Variable In A Different File Without Being Instructed To Do So"