我是棱角分明的初学者,不知道如何将factory
调入controller
。请检查下面的代码。我不知道这是正确的方式。请指导
HTML
<div class="cart" ng-controller="cartWatch">
<table width="100%">
<tr ng-repeat="pro in item">
<td>Name : {{pro.title}}</td>
<td>Quantity : {{pro.quantity}} <input type="text" ng-model="pro.quantity"></input></td>
<td>Price : {{pro.price | currency : '₹'}}</td>
</tr>
</table>
<div class="total">
total Price : <strong>{{totalPrice()}}</strong> <br>
Discount : <strong>{{bill.discount}}</strong> <br>
You Pay : <strong>{{subTotal()}}</strong>
</div>
</div>
SCRIPT
var appProduct = angular.module('myProduct', []);
appProduct.factory('Items', function() {
var items = {};
items.query = function() {
return [
{title: 'Paint pots', quantity: 8, price: 3.95},
{title: 'Polka dots', quantity: 17, price: 12.95},
{title: 'Pebbles', quantity: 5, price: 6.95}
];
};
return items;
});
appProduct.controller('cartWatch', function($scope, Items){
$scope.bill = {};
$scope.totalBeforeDiscount = {};
$scope.totalPrice = function(){
var total = 0;
for (var i = 0; i <= $scope.item.length - 1; i++) {
total += $scope.item[i].price * $scope.item[i].quantity;
}
return total;
}
})
上面的代码在控制台中给出了以下错误
TypeError: Cannot read property 'length' of undefined
at $scope.totalPrice (controller.js:105)
at n.$digest (angular.min.js:142)
at n.$apply (angular.min.js:145)
at angular.min.js:21
at Object.invoke (angular.min.js:41)
at c (angular.min.js:21)
at yc (angular.min.js:21)
at ee (angular.min.js:20)
at angular.min.js:313
答案 0 :(得分:1)
您遗失了两件事,您从不在工厂消耗您的方法,并且您没有考虑控制器方法中工厂退回的物品。
<强>工厂:强>
appProduct.factory('Items', function() {
var items = {};
return {
query: function() {
return [{
title: 'Paint pots',
quantity: 8,
price: 3.95
}, {
title: 'Polka dots',
quantity: 17,
price: 12.95
}, {
title: 'Pebbles',
quantity: 5,
price: 6.95
}];
}
}
});
<强>控制器:强>
appProduct.controller('cartWatch', function($scope, Items){
$scope.items = Items.query();
$scope.bill = {};
$scope.totalBeforeDiscount = {};
$scope.totalPrice = function(){
var total = 0;
for (var i = 0; i <= $scope.items.length - 1; i++) {
total += $scope.items[i].price * $scope.items[i].quantity;
}
$scope.totalBeforeDiscount =total;
}
})
这是工作Plunker
答案 1 :(得分:0)
使用此
var appProduct = angular.module('myProduct', []);
appProduct.factory('Items', function() {
var items = {};
items.query = function() {
return [
{title: 'Paint pots', quantity: 8, price: 3.95},
{title: 'Polka dots', quantity: 17, price: 12.95},
{title: 'Pebbles', quantity: 5, price: 6.95}
];
};
return items.query;
});
appProduct.controller('cartWatch', ['$scope', '$Items', function ($scope, Items) {
$scope.bill = {};
$scope.totalBeforeDiscount = {};
$scope.totalPrice = function(){
var total = 0;
for (var i = 0; i <= $scope.items.length - 1; i++) {
total += $scope.items[i].price * $scope.item[i].quantity;
}
return total;
}
}]);