Oam*_*Psy 4 javascript angularjs angularjs-scope angular-services
通常我写SPA并在控制器之间共享数据对于服务来说很简单.
我没有使用SPA格式(不使用ng-view),并尝试在页面之间共享数据,但在加载第二页(获取数据)时为空.
PAGE1(index.html):
<div ng-controller="CreateList">
<input type="text" ng-model="myValue">
<div ng-click="share(myValue)">Share</div>
</div>
Run Code Online (Sandbox Code Playgroud)
第2页:
<div ng-controller="GeList">
<p>{{ sharedData }}</p>
</div>
Run Code Online (Sandbox Code Playgroud)
JS:
app.controller('CreateList', function($scope, $location, $http, serviceShareData) {
$scope.share= function (selectedValue) {
if (selectedValue === undefined ) {
console.log ("its undefined");
}
else {
console.log (selectedValue);
serviceShareData.addData(selectedValue);
window.location.href = "PAGE2.html";
}
}
});
app.controller('GeList', function($scope, $location, $http, serviceShareData) {
$scope.sharedData = serviceShareData.getData();
console.log($scope.sharedData);
});
app.service('serviceShareData', function() {
var myData = [];
var addData = function(newObj) {
myData.push(newObj);
}
var getData = function(){
return myData;
}
return {
addData: addData,
getData: getData
};
});
Run Code Online (Sandbox Code Playgroud)
这是一个傻瓜:http://plnkr.co/edit/6VHJhirnHZxBpKOvqzI6?p =preview
有多种方法可以在页面之间共享数据 - 本地存储,会话存储,indexedDB,cookie,或者您甚至可以将数据作为参数传递给您:
window.location.href = 'page2.html?val=' + selectedValue;
Run Code Online (Sandbox Code Playgroud)
以下是使用sessionStorage查看服务的快速示例:
app.service('serviceShareData', function($window) {
var KEY = 'App.SelectedValue';
var addData = function(newObj) {
var mydata = $window.sessionStorage.getItem(KEY);
if (mydata) {
mydata = JSON.parse(mydata);
} else {
mydata = [];
}
mydata.push(newObj);
$window.sessionStorage.setItem(KEY, JSON.stringify(mydata));
};
var getData = function(){
var mydata = $window.sessionStorage.getItem(KEY);
if (mydata) {
mydata = JSON.parse(mydata);
}
return myData || [];
};
return {
addData: addData,
getData: getData
};
});
Run Code Online (Sandbox Code Playgroud)
普兰克在这里.
| 归档时间: |
|
| 查看次数: |
15472 次 |
| 最近记录: |