且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-13 19:54:49

在某些情况下 $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);
  }
}]);

这是一个工作示例