Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I am using a Factory in Angular JS to share data between 2 controller/sub-views using router-ui.

Factory:

app.factory('SharedData', function() {
  return {data: {}};
})

JobsController:

app.controller("JobsController", function($scope, $http, $resource, $location, $stateParams, JobsService, $state, SharedData) {
  SharedData.data = JobsService.query();

  $scope.data = SharedData.data; 
});

NavController:

app.controller("navController", function($scope, $state, SharedData) {
  $scope.data = SharedData.data;
});

jobs.html

{{data.jobs.length}} // this updates fine

nav.html

{{data.jobs.length}} // this does not update

Instead I have to do this:

NavController:

app.controller("navController", function($scope, $state, SharedData) {
  $scope.data = SharedData;
});

jobs.html

{{data.jobs.length}} // this works fine

nav.html

{{data.data.jobs.length}} // this now works but not sure why the extra 'data' is needed?

Obviously I'm doing something wrong here but I can't figure out what despite googling for quite a few hours... can anyone help?

share|improve this question
    
I suggest loading 'jobs' data in SharedData before instantiating the two controllers. This can be done by using StateProvider's resolve property. – user 013948 14 hours ago

This quirk has to do with the order of allocation.

When SharedData is initialized, it is an object with a single property, data, which is an empty object.

When navController is initialized, it's $scope.data is set equal to the empty object SharedData.data.

When jobsController is initialized, it replaces SharedData.data with an entirely different object. After this, $scope.data is set to equal this new object, but navController is still pointing to the original empty object.

In your second example, navController isn't pointing to this object soon to be replaced. Instead, it is pointing to the SharedData object itself, so $scope.data.data will always resolve whichever object currently exists on SharedData.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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