问题
What is the best way to share some data across all controllers and scopes of my Single page application ?
Let say i have a small set of data I want to be able to access everywhere, and I don't want to query the database every time I need it.
回答1:
Shared data services seems to be the best aproach for your case. There is $rootScope
as a global scope, but, $rootScope
shoudn't be used for such thing due to performance issues. $rootscope
is part of angular digest cycle, so when you add something to it, you are also adding something more to be checked. Therefore, it's not recommended to use unless it's extremely necessary.
For example, for simple services:
app.service('SharedDataService', function () {
var Data = {
field1: 'qweqwe',
field2: '12312'
};
return Data;
});
For complex services with async operations:
app.service('SharedDataService', function () {
var self = this;
this.getData = function () {
if(self.cachedData){
return $q.resolve(self.cachedData);
}
return $http.get('my-data-url').then(function (response) {
self.cachedData = response.data;
return self.cachedData;
});
};
});
And the controller:
app.controller('MyController', function ($scope, SharedDataService) {
SharedDataService.getData().then(function (data) {
$scope.data = data;
});
});
回答2:
The data to be stored in $rootscope variable
(or)
data to be stored in services
回答3:
Best to use service say commonService
and after getting data from database store on a variable inside the service like this
this.dbDataSearch = function(parameters){
// Search record from database
this.resultData = data;
}
In Controller 1:
$scope.data = commonService.resultData;
In Controller 2:
$scope.data = commonService.resultData;
In Controller n:
$scope.data = commonService.resultData;
回答4:
In angularJS you can perform this operation in different ways. either you can use $rootscope or you can broadcast data or you can use services or factories.
But the bet preferred way is to use services. First thing is it's easy. You can use the same service on every controller to access the data.
If you want to know more about angularjs services please check below link.
http://viralpatel.net/blogs/angularjs-service-factory-tutorial/
来源:https://stackoverflow.com/questions/40087220/angularjs-how-do-i-share-data-accross-all-pages-and-controller-of-my-spa