在更新Angular工厂变量时更新控制器变量 [英] Update controller variable on Updating Angular factory variable

查看:68
本文介绍了在更新Angular工厂变量时更新控制器变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题. 我的工厂里有一个物体,如下所示

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

User: {
   EmailAddress: ""
}

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

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.
            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并期望它自动更新.
另一方面,对象受引用约束,因此您可以执行以下操作:

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

这篇关于在更新Angular工厂变量时更新控制器变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆