不能给只读Angular赋值

Cannot assign read only Angular

本文关键字:赋值 Angular 只读 不能      更新时间:2023-09-26

我有这个控制器:

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接受两个参数,一个变量和一个函数,该函数有oldValuenewValue(不是$scope)。在这里查看如何使用$watch的信息。

$watch回调函数的第二个参数是旧值,而不是$scope, scope作为第三个参数传递,因此您的calculateDiscount函数可能看起来像

calculateDiscount(newValue,oldValue,$scope)

但是注意,因为calculateDiscount已经可以访问$scope,因为它是在外部函数作用域中定义的,所以不需要第三个参数。也可以直接用

calculateDiscount(newValue,oldValue)

但是如果在控制器外部定义了calculateDiscount,则需要使用第三个参数。

美元看参考