2017-02-22 110 views
0

如果总数大于1,我想访问总属性并将名词属性更改为“条目”,并使用总数和名词更新句子属性属性。Javascript/AngularJS - 在初始化期间访问对象的属性

这里是我的代码:

$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 i尚未初始化?任何人都可以为我提供一个更好的方法,如果这个不可能的话?

回答

0

你不能使用它的声明之前

试试这个

var total = 0 

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

你可以这样做:

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

我已经实现了通过以下方式:

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