angularjs – 更新Angular工厂变量时更新控制器变量

前端之家收集整理的这篇文章主要介绍了angularjs – 更新Angular工厂变量时更新控制器变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
嗨,我有一个问题.
我的工厂里有一个对象如下

User: {
   EmailAddress: ""
}

每当我进行http调用时,我想更新User.EmailAddress whith返回的值.在工厂内做这件事的最佳方法是什么?所以在控制器级别我可以将$scope.Email绑定到工厂变量.这就是我现在正在做的事情

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.
            User.EmailAddress=response.data.Email;
            return response.data
        });
        return promise;
        // Return the promise to the controller
    }
}

在控制器中

AccountFactory.GetlogonModel().then(function (data) {
  $scope.logonModel = data;
},function (err) {
  console.log(err.reason);
  alert(err.reason);
});

解决方法

原始类型(如字符串)不受引用约束.因此,您无法直接将范围属性绑定到EmailAddress,并期望它自动更新.
另一方面,对象通过引用绑定,因此您可以执行以下操作:

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

  function getlogonModel() {
    $http.get(...).then(function (response) {
      User.EmailAddress = response.data.Email;
    });
  }

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

  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`
});

猜你在找的Angularjs相关文章