不能给只读Angular赋值
Cannot assign read only Angular
我有这个控制器:
cart.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视图中显示数据:
<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'
当设置了其他变量时,计算出的总价值很好。但我不明白为什么会这样,因为它的定义是正确的。这段代码只是约曼项目的一部分。有人知道是什么问题吗?
我认为问题与您的功能$scope.calculateDiscount
有关。
$scope.$watch
接受两个参数,一个变量和一个函数,该函数有oldValue
和newValue
(不是$scope
)。在这里查看如何使用$watch
的信息。
$watch回调函数的第二个参数是旧值,而不是$scope, scope作为第三个参数传递,因此您的calculateDiscount函数可能看起来像
calculateDiscount(newValue,oldValue,$scope)
但是注意,因为calculateDiscount已经可以访问$scope,因为它是在外部函数作用域中定义的,所以不需要第三个参数。也可以直接用
calculateDiscount(newValue,oldValue)
但是如果在控制器外部定义了calculateDiscount,则需要使用第三个参数。
美元看参考
相关文章:
- Javascript变量赋值|
- 无法为打字稿字典赋值
- Javascript-根据赋值顺序,按键合并对象数组
- Javascript:应为赋值或函数调用,但实际看到的却是表达式
- 如何通过json对象数组为嵌套对象赋值
- 赋值后的回调函数
- ||(OR)运算符如何在赋值中工作
- 可以使用属性赋值实现多个函数
- chrome.storage.sync.get未返回值-Angular服务
- 赋值 Angular 2 中 Http 订阅方法返回的值
- 为什么控制器中的数组赋值会破坏Angular代码
- 赋值Angular $http.获取对变量的调用对象
- Angular.js:是否不能将解析承诺的属性赋值给$scope ?
- 为什么angular js不使用最后赋值
- Angular Service——返回私有值vs .引用私有值赋值
- 为什么赋值在Angular表达式中不总是有效
- 在Angular中,为什么要把函数赋值给变量?
- 通过javascript给angular控制器赋值
- 不能给只读Angular赋值
- Angular指令控制器——等待属性的赋值/求值