當我從page1.html導航到angularjs中的page2.html並返回到page1.html時,我遇到問題,我的頁面模型數據消失了,我怎麼能保持這一點,請在這件事情上幫助我。如何在不同的視圖間導航,同時在angularjs中維護視圖模型數據
我已經看到一些類似的問題,但無法理解如何在使用服務的AngularJS中實現此任務。
當我從page1.html導航到angularjs中的page2.html並返回到page1.html時,我遇到問題,我的頁面模型數據消失了,我怎麼能保持這一點,請在這件事情上幫助我。如何在不同的視圖間導航,同時在angularjs中維護視圖模型數據
我已經看到一些類似的問題,但無法理解如何在使用服務的AngularJS中實現此任務。
如果我理解正確,您希望跨應用程序的兩個不同視圖共享某種狀態。有很多方法可以實現這一點,正如你上面所說的,你可以使用一項服務。
var app = angular.module('myApp', []);
app.service('myService', function(){
var data;
this.setData = function(d){
data = d;
}
this.getData = function(){
return data;
}
});
app.controller('myCtrl1', function($scope, myService){
$scope.data = myService.getData();
//do something
});
app.controller('myCtrl2', function($scope, myService){
$scope.data = myService.getData();
//do something
});
服務是單身,被實例化一次,然後通過角,每次緩存您需要具體的數據,你可以注入和呼叫提供的方法。
在您的代碼中使用本地存儲概念時,它會將所有數據存儲在瀏覽器中,當您瀏覽頁面時,您可以從瀏覽器獲取所有數據。檢查下面的示例代碼。
<html ng-app="app">
<head>
<script data-require="[email protected]" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
<script src="https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js"></script>
<script>
angular.module('app', [
'ngStorage'
]).
controller('Ctrl', function(
$scope,
$localStorage
){
$scope.$storage = $localStorage.$default({
x: 42
});
});
</script>
</head>
<body ng-controller="Ctrl">
<button ng-click="$storage.x = $storage.x + 1">{{$storage.x}}</button> + <button ng-click="$storage.y = $storage.y + 1">{{$storage.y}}</button> = {{$storage.x + $storage.y}}
</body>
</html>
嘗試設置在相同的應用程序都HTML,這樣的數據不會lose.use路由視圖中顯示了HTML,
如果從一個改變HTML到另一個絕對數據丟失會角度框架只適用於單頁應用程序....
app.run(function($rootScope) {
$rootScope.name="something";
});
//Controller
app.controller('myController',function ($scope,$rootScope){
console.log("Name in scope ",$scope.name);
});