Javascript / AngularJS - 在初始化期间访问对象的属性

时间:2017-02-22 04:03:47

标签: javascript angularjs

我想访问total属性并将名词属性更改为" items"如果总数大于1.并且还使用total和noun属性更新句子属性。

这是我的代码:

$scope.itemCounter = {
            total: 0,
            noun: $scope.itemCounter.total <= 1 ? "item" : "items",
            sentence: $scope.itemCounter.total+" "+$scope.itemCounter.noun+" remaining"
        };

但它给了我这个错误:

Cannot read property 'total' of undefined

预期输出应为:

$scope.itemCounter.sentence = "0 item remaining";

是不是因为$ scope.itemCounter尚未初始化?如果不可能的话,有人能为我提供更好的方法吗?

2 个答案:

答案 0 :(得分:0)

您无法在声明之前使用它

试试这个

   var total = 0

$scope.itemCounter = {
            total: 0,
            noun: total <= 1 ? "item" : "items",
            sentence: total+" "+$scope.itemCounter.noun+" remaining"
        };

答案 1 :(得分:0)

你可以这样做:

$scope.itemCounter = {
            total: 0,
            noun: $scope.itemCounter.total <= 1 ? "item" : "items",
            get sentence(){ 
           return $scope.itemCounter.total+" "+$scope.itemCounter.noun+" remaining"
         }
  };