2017-05-15 32 views
0

我正在研究從模板A到模板B的應用程序返回到模板A.在模板A上,用戶單擊按鈕以獲取模板B.在模板B上,用戶添加一個數量然後點擊提交。該程序然後返回到模板A並顯示在模板B中輸入的內容,但提交的編號未在範圍內更新並顯示爲空。由於某種原因,當我從模板B啓動應用程序到模板A時,範圍被更新。

我使用的是工廠

.factory('myService', function(){ 
    var budget = { 
    limit: null 
    }; 
    function set(data){ 
    budget.limit = data; 
    } 
    function get(){ 
    return budget.limit; 
    } 
    return{ 
    set: set, 
    get: get, 
    print: console.log(budget.limit) 
    } 
}) 

這裏是我的模板A代碼調用BudgetCalc

<ion-view view-title="BudgetCalc"> 
    <ion-content class="padding"> 
    <a href="#/tab/dash/addBudget"><button>Start Budgeting</button></a> 
    <h2>Your Limit is {{limit}}</h2> 
    </ion-content> 
</ion-view> 

而模板B命名addBuget

<ion-view view-title="Add a Budget"> 
    <ion-content> 
     <label class="item item-input"> 
      <span class="input-label">Set Spending Limit</span> 
      <input type="number"ng-model="limit"> 
     </label> 
     <button ui-sref="tab.budget" ng-click="setLimit(limit)">Submit</button> 
     <br><h2>Your Limit is: {{limit}}</h2> 
    </ion-content> 
</ion-view> 

這裏是我的控制器,用於兩個模板

.controller('BudgetCtrl', function($scope, myService) { 
    $scope.limit = myService.get(); 
    console.log("This is your limit " + $scope.limit); 
}) 

.controller('SetLimitCtrl', function($scope, myService){ 
    $scope.setLimit = function(limit){ 
    if (limit != null) { 
     myService.set(limit); 
     console.log(myService.print); 
    } 
    } 
}) 
+0

每次回去的時間查看A,是BudgetCtrl運行的console.log? – yBrodsky

+0

不,它只在第一次運行。返回時不再顯示。 –

+0

當導航回到視圖A時,添加重新加載選項。 $ state.go('viewA'),{},{reload:true}) – yBrodsky

回答

0

您可以使用本地存儲

.controller('SetLimitCtrl', function($scope, $localstorage){ 
    $scope.setLimit = function(limit){ 
    if (limit != null) { 
     $localstorage.set("limit",limit); 
     console.log($localstorage.get("limit")); 
    } 
    } 
}) 

.controller('BudgetCtrl', function($scope, $localstorage) { 
    $scope.limit = $localstorage.get("limit"); 
    console.log("This is your limit " + $scope.limit); 
    //// Dont forgot to clear limit when you complete the further process 
}) 

廠Localsoarage共享控制器之間的數據:

.factory('$localstorage', ['$window', function ($window) { 
       return { 
        set: function (key, value) { 
         $window.localStorage[key] = value; 
        }, 
        get: function (key, defaultValue) { 
         return $window.localStorage[key] || defaultValue; 
        }, 
        setObject: function (key, value) { 
         $window.localStorage[key] = JSON.stringify(value); 
        }, 
        getObject: function (key, nulled) { 
         nulled = '[]'; 
         try { 
          return JSON.parse($window.localStorage[key] || '[]'); 
         } catch (e) { 
         } 
        }, 
        delete: function (key) { 
         $window.localStorage.removeItem(key); 
        }, 
       }; 
      }])