基本上,当用户提交对数据进行计算并将其存储在变量中时。当它在一个控制器中时,我有它工作,但现在我需要在页面之间拆分它。我想用一项服务来做这件事。正如你将看到的,我真的很困惑,我知道我基本上完全做错了。我不确定我在哪里误入歧途,或者我应该调查一下以更好地处理我的误解 - 任何帮助都非常感激。即使只是一个基本指针也不错:
.factory('meals', function() {
var data = {
basePrice: 0,
taxRate: 0,
tipPercentage: 0,
mealCount: 0,
tipTotal: 0,
averageTip: 0,
subtotal: 0,
tip: 0,
tipTotal: 0,
total:0
}
function set(data) {
savedData = data;
}
function get(){
return savedData;
}
return {
set: set,
get: get
}
})
.controller('HomeCtrl', [function(meals) {
}])
.controller('MealCtrl', [function(meals) {
var ws = this;
meals.set();
ws.data = meals.get();
ws.submit = function(){
ws.tax_rate= ws.taxRate/100;
ws.tip_rate= ws.tipPercentage/100;
ws.subtotal= ws.basePrice*ws.tax_rate;
ws.tip = ws.basePrice*ws.tip_rate;
ws.total = ws.basePrice+ws.subtotal+ws.tip;
ws.mealCount+=1;
ws.tipTotal+=ws.tip;
ws.averageTip=(ws.tipTotal+ws.tip)/ws.mealCount;
items.tipTotal=ws.tipTotal;
items.mealCount=ws.mealCount;
items.averageTip=ws.averageTip;
};
ws.cancel = function(){
ws.basePrice='';
ws.taxRate='';
ws.tipPercentage='';
};
ws.double = function(value){return value*2;};
}]).controller('EarningsCtrl', [function(meals) {
和HTML:
<h2>Enter the Meal Details</h2>
<form name="Calculator" ng-submit="ws.submit()">
<p>Base Meal Price:</p>
<input type="number" ng-model="ws.basePrice" required> <br>
<p>Tax Rate: %</p>
<input type="number" ng-model="ws.taxRate" required> <br>
<p>Tip Percentage: %</p>
<input type="number" ng-model="ws.tipPercentage" required> <br>
<button>Submit</button>
</form>
<button ng-click="ws.cancel()">Cancel</button>
<h2>Customer Charges</h2>
<p>Base Price {{ws.data.basePrice | currency}}</p>
<p>Subtotal {{ws.subtotal | currency}}</p>
<p>Tip {{ws.tip | currency}}</p>
<p>Total {{ws.total | currency}}</p>