如何将数据共享给所有控制器?
我有一个控制器可以从服务器(file.json)中提取要共享给其他控制器的数据
sampleApp.controller('PhoneListCtrl',
['$scope', '$http',
function($scope, $http) {
$http.get('App_Data/phonelist.json').
success(function(returnDataFrmJson){
$scope.phonesScope = returnDataFrmJson;
});
}]);
将访问第一个共享数据的控制器
sampleApp.controller('AddIPhoneController',
['$scope', '$http',
function($scope, $http) {
$scope.newInput= 'sample text';
$scope.sharedText= dataFromSharedControll;
}]);
显示数据的html文件。
{{newInput}} {{sharedText}}
那么,有适合你的各种选项喜欢使用:$sessionStorage
,localStorage
,appConstant
,$localStorage
等等。
您甚至可以使用Factory
和在控制器之间共享数据Services
。我将给您一个使用的简单示例$sessionStorage.
为了使用$sessionStorage
或$localStorage
,您需要注入ngStorage。
首先在index.html中,包括源:
<script src="https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js"></script>
然后在模块定义中,注入ngStorage:
var sampleApp = angular.module('Your App Name', ['ngStorage']);
并且,在您的controllers
:
sampleApp.controller('PhoneListCtrl',
['$scope', '$http', '$sessionStorage',
function($scope, $http,$sessionStorage) {
$http.get('App_Data/phonelist.json').
success(function(returnDataFrmJson){
$scope.phonesScope = returnDataFrmJson;
$sessionStorage.sharedValue = returnDataFrmJson;//keeping the value in session
});
}]);
controller
将访问第一个共享数据
sampleApp.controller('AddIPhoneController',
['$scope', '$http','$sessionStorage',
function($scope, $http,$sessionStorage) {
$scope.newInput= 'sample text';
$scope.sharedText= $sessionStorage.sharedValue;
}]);
然后在您的View
:
{{newInput}}{{sharedText}}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句