在angualrjs的工厂中获取和设置值 [英] getting and setting value in factory in angualrjs

查看:24
本文介绍了在angualrjs的工厂中获取和设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的工厂:

.factory('userService',()){
  var user = {};
  return {

  getFirstname : function () {
    return user.firstname;
  },

  setFirstname : function (firstname) {
    user.firstname = firstname;
  }

}

我在我的两个控制器 MainCtrl 和 AccountEditCtrl 中使用此服务我在 MainCtrl 中使用 getFirstname() 并在 AccountEditCtrl 中使用 setFirstname

And I'm using this service in my two controllers MainCtrl and AccountEditCtrl I'm using my getFirstname() in my MainCtrl and setFirstname in AccountEditCtrl

.controller('MainCtrl',['userService', function(userService){
  $scope.userName = userService.getFirstName();
}]);

.controller('AccountEditCtrl',['userService', function(userService){
      userService.setFirstname("New First Name");
}]);

我的问题是,当我使用 userService.setFirstname() 时,$scope.userName 在 MainCtrl 中不会改变.

My problem is that when I use the userService.setFirstname() the $scope.userName don't change in MainCtrl.

推荐答案

在某些情况下 $watch 不能与工厂对象一起工作.您可以使用事件进行更新.

In some case $watch is not working with factory object. Than you may use events for updates.

 app.factory('userService',['$rootScope',function($rootScope){
  var user = {};
  return {

  getFirstname : function () {
    return user.firstname;
  },

  setFirstname : function (firstname) {
    user.firstname = firstname;
    $rootScope.$broadcast("updates");
  }

}
}]);
app.controller('MainCtrl',['userService','$scope','$rootScope', function(userService,$scope,$rootScope) {
  userService.setFirstname("bharat");
  $scope.name = userService.getFirstname();
  $rootScope.$on("updates",function(){
    $scope.name = userService.getFirstname();
  });
}]);

app.controller('one',['userService','$scope', function(userService,$scope) {
  $scope.updateName=function(){
    userService.setFirstname($scope.firstname);
  }
}]);

这是一个工作示例

这篇关于在angualrjs的工厂中获取和设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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