加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 18:01:57 所属栏目:安全 来源:网络整理
导读:嗨,我有一个问题. 我的工厂里有一个对象如下 User: { EmailAddress: ""} 每当我进行http调用时,我想更新User.EmailAddress whith返回的值.在工厂内做这件事的最佳方法是什么?所以在控制器级别我可以将$scope.Email绑定到工厂变量.这就是我现在正在做的事情
嗨,我有一个问题.
我的工厂里有一个对象如下

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读