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

问题描述

这是我厂的:

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

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

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

}

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

And I'm using this service in my two controllers MainCtrl and AccountEditCtrlI'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.

推荐答案

在某些情况下,$手表未与工厂对象的工作。比你可以使用更新的事件。

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工厂设定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 19:45