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

17 浏览
0 Comments

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

这个问题已经有答案了:

AngularJS:服务 vs 提供者 vs 工厂

我是angular的新手。所以试图知道如何在两个控制器之间共享数据并搜索Google。我访问了一些页面,发现大多数人使用工厂来共享数据。我想知道是否可以使用服务而不是工厂来实现呢?

第一个例子

  
  
Input is : {{data.firstName}}

Input should also be here: {{data.firstName}} 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;
});

这些例子来自于此URL:在AngularJS控制器之间共享数据

请指导我。

admin 更改状态以发布 2023年5月23日
0
0 Comments

无论哪个API创建它,.service()和.factory()都是单例,您只会得到每个Service的一个实例。

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

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

0