gpt4 book ai didi

javascript - 无法分配只读 Angular

转载 作者:行者123 更新时间:2023-11-28 19:12:12 26 4
gpt4 key购买 nike

我有这个 Controller :

购物车.js

var cart = angular.module('tutorialAngularApp');
cart.factory('Items', function () {


var items = {};
items.query = function () {
return [
{title: 'Paint pots', description: 'Pots full of paint', quantity: 8, price: 3.95},
{title: 'Polka dots', description: 'Dots with polka', quantity: 17, price: 2.95},
{title: 'Pebbles', description: 'Just little rocks', quantity: 5, price: 6.95}
];
};
return items;
});

cart.controller('CartCtrl', function ($scope, Items) {
$scope.bill = {};
$scope.discount = {};
$scope.items = Items.query();

$scope.totalCart = function () {
var total = 0;
for (var i = 0, len = $scope.items.length; i < len; i++) {
total = total + $scope.items[i].price * $scope.items[i].quantity;
}
return total;
};

$scope.subtotal = function () {
return $scope.totalCart() - $scope.discount;
};

$scope.calculateDiscount = function (newValue, $scope) {
$scope.discount = newValue > 100 ? 10 : 0;
};

$scope.$watch($scope.totalCart, $scope.calculateDiscount);
});

我正在尝试在此 html View 中显示数据:

<div>
<div ng-repeat="item in items">
<span>{{item.title}}</span>
<input ng-model="item.quantity">
<span>{{item.price | currency | number: 2}}</span>

<p></p>
<span>{{item.price * item.quantity | currency | number: 2}}</span>

<p></p>
</div>
<div>Total: {{totalCart() | currency}}</div>
<p></p>

<div>Discount: {{discount | currency}}</div>
<p></p>

<div>Subtotal: {{subtotal() | currency}}</div>
<p></p>
</div>

我收到错误

TypeError: Cannot assign to read only property 'discount'

当设置每个其他变量时,可以很好地计算总值。但我不明白为什么会发生这种情况,因为它的定义是正确的。此代码只是 Yeoman 项目的一部分。似乎有人知道问题出在哪里?

最佳答案

我相信问题与您的函数 $scope.calculateDiscount 有关。

$scope.$watch 接受两个参数,一个变量和一个具有 oldValuenewValue 的函数(不是 >$范围)。看看here有关如何使用 $watch 的信息。

关于javascript - 无法分配只读 Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30557012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com