Atul Chaudhary Atul Chaudhary - 1 year ago 108
AngularJS Question

Update controller variable on Updating Angular factory variable

Hi I have got one question.
I have got one object as following in my Factory

User: {
EmailAddress: ""

whenever i make http call I want to update that User.EmailAddress whith returned value. What is the best way of doing it in within the factory? so that at controller level I can just bind my $scope.Email to factory variable. This is what I am doing right now

GetLogOnModel: function () {
if ($location.path().indexOf("login") == 1) {
var promise = $http.get(config.headers.url + "LogOn").then(function (response) {
// The return value gets picked up by the then in the controller.;
return promise;
// Return the promise to the controller

And in Controller

AccountFactory.GetLogOnModel().then(function (data) {
$scope.logOnModel = data;
}, function (err) {

Answer Source

Primitive types (such as strings) are not bound by reference. So you can't bind a scope property to EmailAddress directly and expect it to get automatically updated.
Objects on the other hand are bound by reference, so you could do something like this:

app.factory('AccountFactory', function (...) {
  var User = {
    EmailAddress: null

  function getLogOnModel() {
    $http.get(...).then(function (response) {
      User.EmailAddress =;

  // Init model (or leave it for the controller to init it)

  return {
    User: User,
    getLogOnModel: getLogOnModel

app.controller('someCtrl', function (..., AccountFactory) {
  $scope.user = AccountFactory.User;
  // Now you can reference `$scope.user.EmailAddress`
  // and it will be kept in sync with `AccountFactory.User.EmailAddress`