AngularJS: 为什么人们更喜欢使用工厂来在控制器之间共享数据
AngularJS: 为什么人们更喜欢使用工厂来在控制器之间共享数据
这个问题已经有答案了:
我是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日