AngularJS:为什么人们更喜欢工厂在控制器之间共享数据

时间:2017-06-09 14:30:46

标签: angularjs

我是棱角分明的新人。所以试图知道如何在两个控制器之间共享数据和搜索谷歌。我访问了几页,发现大多数时候人们使用工厂来共享数据。我只是想知道我们不是可以通过服务代替工厂吗?

第一个例子

<div ng-controller="FirstCtrl">
  <input type="text" ng-model="data.firstName">
  <br>Input is : <strong>{{data.firstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
  Input should also be here: {{data.firstName}}
</div>

myApp.factory('MyService', function(){
  return {
    data: {
      firstName: '',
      lastName: ''
    },
    update: function(first, last) {
      // Improve this method as needed
      this.data.firstName = first;
      this.data.lastName = last;
    }
  };
});

// Your controller can use the service's update method
myApp.controller('SecondCtrl', function($scope, MyService){
   $scope.data = MyService.data;

   $scope.updateData = function(first, last) {
     MyService.update(first, last);
   }
});

第二个例子

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 ){

});

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

示例来自此网址Share data between AngularJS controllers

请指导我。

1 个答案:

答案 0 :(得分:2)

.service()和.factory()都是单例,因为无论API创建了什么API,您都只能获得每个服务的一个实例。

请记住.service()只是一个构造函数,它用new调用,而.factory()只是一个返回值的函数。

使用.factory()为我们提供了更多的功能和灵活性,而.service()本质上是.factory()调用的“最终结果”。 .service()通过在函数上调用new来提供返回值,这可能是限制的,而.factory()在此编译过程之前是一步,因为我们选择要实现和返回的模式。

相关问题