This article mainly introduces how each independent JS file or different controller realizes data sharing and interaction. It has a certain reference value, let’s take a look with the editor below
First, create a factory to store and retrieve your data (you can create a separate js file and name it according to semantics Such as: dataService.js. Then introduce this JS file on your main page)
<!--引入到你的主页面里面--> <script src="dataService.js"></script> 创建一个factory 'use strict'; angular.module('myApp') .factory('datadService',['$window',function($window) { return{ //存储单个属性 set :function(key,value){ $window.localStorage[key]=value; }, //读取单个属性 get:function(key,defaultValue){ return $window.localStorage[key] || defaultValue; }, //存储对象,以JSON格式存储 setObject:function(key,value){ $window.localStorage[key]=JSON.stringify(value); }, //读取对象 getObject: function (key) { return JSON.parse($window.localStorage[key] || '{}'); } } }]);
Second, inject the method module [datadService] you created into the controller you want. The following controller is [productCtrl]. Next we create a set.js file with the following code:
'use strict'; angular.module('myApp').controller( 'productCtrl', [ '$scope','datadService', function($scope, datadService) { $scope.appiAppType = 1; //这里面$scope.appiAppType的赋值同样可以通过$http.post或者$http.get //等方法返回的参数去赋值,例子如下: //$http.post('这里是你所要访问的接口【URL】',这里是你想要上传的参数).success(function(data){ // $scope.appiAppType = data; //}); datadService.setObject("lodinData", $scope.appiAppType);// 将你获取来的数据存储到你之前创建的【datadService】中,这里面的【lodinData】是KEY(个人理解就是你把数据存到大箱子里面这个箱子就是【datadService】,为了方便在这个箱子里面更好的寻找你想要的数据就给他一个小标签,那就是【lodinData】) } ]);
Third, how to obtain stored data in different controls Okay, let’s create a get.js with the following code:
'use strict'; //首先大家要把之前创建好的模块也就是那个装数据的箱子【datadService】放到这个控制器中(也就是模块注入) //其次大家通过之前咱们设定的标签【lodinData】,用【getObject('key')】方法取到你想要的数据; //具体实现就一行代码:datadService.getObject('lodinData');「注:把箱子拿出来(datadService)用(getObject)去拿你的这个(lodinData)标签下的数据」 angular.module('myApp').controller( 'completeCtrl', [ '$scope', 'datadService', function($scope, datadService) { //我们这里取到来上面已经存好的数据:【datadService.getObject('lodinData');】并且把这个数据赋值给了【$scope.LoginList】 $scope.LoginList = datadService.getObject('lodinData'); //这里大家可以打印一下$scope.LoginList 看看里面是什么; alert(JSON.stringify($scope.LoginList)) } ]);
The above is the detailed content of Detailed explanation of local storage instances of AngularJs data. For more information, please follow other related articles on the PHP Chinese website!