2

Some application state information need to be stored in an Angular service so as to be globally accessed.

app.value('identity', {});

Then in a controller of my first view after log in. I make a GET api call to collect application state info from the server side. In the success callback, transfer the data into my global variable (service).

function successCallback(data) {
    identity.username = data.username;
    identity.email = data.email;
}

I assumed the identity will hold the data throughout my application. But it is not the case! In my other views, I inject identity into the controller

app.controller('anotherController', ['identity', anotherController];
function anotherController(identity){
    // access identity here.
    $scope.username=identity.username;
}

The first time I came to that view. username is correctly displayed on the page. But after a refresh, it appears the identity is null again! What can we do to make the value really persistent?

2
  • "after a refresh" do you mean an F5-style refresh? Commented Jul 7, 2014 at 19:31
  • 1
    Services are singletons in an angular app, but the whole app restarts with an F5. You could maintain the state client side with localStorage. Commented Jul 7, 2014 at 19:45

1 Answer 1

2

You're pointing the var identity to a new object that angular doesn't know about so it can't take that new value to another controller. I'd assign the callback's response to a property on identity:

app.value('identity', { data: null });

...

funciton successCallback(data) {
  // here, not overwriting identity, but editing a property
  identity.data = data;
}

controller:

app.controller('anotherController', ['identity', anotherController];
  function anotherController($scope, identity){

  // add the svc to the scope so you can access its properties later
  $scope.identity = identity;
}

html template:

{{ identity.data | json }}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply. Found another issue after marking it as the correct answer. I have updated the question a bit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.