我正在处理从模板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 :(得分:0)
您可以使用localstorage
在控制器之间共享数据.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
})
Factory 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);
},
};
}])