在angularjs的工厂中获取和设置值

getting and setting value in factory in angualrjs

这是我的工厂:

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

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

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

}

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

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

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

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

你有两种选择来克服这个问题。

解决方案 1:

正在控制器中添加手表。

.controller('MainCtrl',['userService', function(userService) {

    $scope.userName = userService.getFirstName();

    $scope.$watch(function() {
        return userService.getFirstName();
    }, function(newValue) {
       $scope.username = newValue;
    });
}]);

解决方案二:

.controller('MainCtrl',['userService', function(userService) {

    $scope.getUsername = function() {
        userService.getFirstName();
    };

}]);

现在你的视图应该直接调用这个函数。

<div class="username">{{getUsername()}}</div>

现在,根据 Angular 的文档,每当函数调用的 return 值发生变化时,Angular 将更新视图中的值。

你应该这样使用 $ watch:

.factory('userService',()){
  return {
     user:{ 'firstname': 'defaultFirstname'},
     getFirstname : function () {
       return user.firstname;
     },

     setFirstname : function (firstname) {
       user.firstname = firstname;
     }
}
.controller('MainCtrl',['userService', function(userService){
  $scope.userName = userService.getFirstname();
  $scope.$watch('userService.user.firstname', function (newVal) {
      $scope.userName = newVal;
  });
}]);

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

当跨控制器使用相同的对象时,您必须使用 .service 方法定义您的服务,如下所示:

.service('userService',function(){
  this.user = {};

  this.getFirstname = function () {
    return this.user.firstname;
  };

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

});

在某些情况下 $watch 无法使用工厂对象。比您可以使用事件进行更新。

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

Here is a working example

广播事件使用$timeout。它会帮助你。

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

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

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

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

带有 getter 和 setter 示例代码的示例工厂

<div ng-app="myApp">
<div ng-controller="FirstCtrl">
  <br>Input is : <strong>{{data.firstName}}</strong>
  <button ng-click="setData()">setData</button>
</div>
<hr>

<div ng-controller="SecondCtrl">
  Input should also be here: {{data.firstName}}
  <button ng-click="getData()">getData</button>
</div>
</div>

var myApp = angular.module('myApp', []);

myApp.factory('Data', function(){

    var service = {
        FirstName: '',
        setFirstName: function(name) {
            // this is the trick to sync the data
            // so no need for a $watch function
            // call this from anywhere when you need to update FirstName
            angular.copy(name, service.FirstName); 
        }
    };
    return service;
});


// Step 1 Controller
myApp.controller('FirstCtrl', function( $scope, Data ){
$scope.setData = function() {
        Data.FirstName='Tridip';
    };
});

// Step 2 Controller
myApp.controller('SecondCtrl', function( $scope, Data ){
    $scope.FirstName = Data.FirstName;

$scope.getData = function() {
        alert('get data '+Data.FirstName)
    };
});