【发布时间】:2017-11-11 15:03:16
【问题描述】:
我是角度方面的新手。所以想知道如何在两个控制器之间共享数据并搜索谷歌。我访问了几页,发现大多数时候人们使用工厂来共享数据。我只是想知道我们不能通过服务而不是工厂来做吗?
第一个例子
<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
请指导我。
【问题讨论】:
-
我建议你阅读这篇关于 Angular 服务与工厂的简单明了的文章。 blog.thoughtram.io/angular/2015/07/07/…
-
您的解释很好,但我是新手,所以仍然不明白为什么有人会写工厂来共享数据.....为什么不提供服务?如果可能的话,试着用更简单的方法向我解释。谢谢
标签: angularjs