2016-11-02 32 views

回答

2

如果我理解正確,您希望跨應用程序的兩個不同視圖共享某種狀態。有很多方法可以實現這一點,正如你上面所說的,你可以使用一項服務。

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 
}); 

服務是單身,被實例化一次,然後通過角,每次緩存您需要具體的數據,你可以注入和呼叫提供的方法。

0

在您的代碼中使用本地存儲概念時,它會將所有數據存儲在瀏覽器中,當您瀏覽頁面時,您可以從瀏覽器獲取所有數據。檢查下面的示例代碼。

<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> 
0

嘗試設置在相同的應用程序都HTML,這樣的數據不會lose.use路由視圖中顯示了HTML,


如果從一個改變HTML到另一個絕對數據丟失會角度框架只適用於單頁應用程序....

0
app.run(function($rootScope) { 
    $rootScope.name="something"; 
}); 
//Controller 
app.controller('myController',function ($scope,$rootScope){ 
console.log("Name in scope ",$scope.name); 
}); 
相關問題