AngularJs-控制器内的计算

时间:2015-05-09 22:58:38

标签: angularjs ionic

您好我希望能够在包含元素的控制器内计算一些数字。这是尝试过的(离子APP太btw):

.controller('tasksCtrl', function($scope) {
  $scope.tasksCollection = [
    { info: 'Go studying', measured: 'no', total: 1, done: 1, id: 1 },
    { info: 'Go to the beach', measured: 'no', total: 1, done: 1, id: 2},
    { info: 'Run', measured: 'yes', total: 30, done: 15, id: 3}
    ];

    $scope.calculateProductivity = function(){
    var total = 0;
    for(var i = 0; i < $scope.tasksCollection.length; i++){
        var product = $scope.tasksCollection[i];
        total += (tasksCollection.done / tasksCollection.total);
      }
      return total;
    };
})

,页面有:

 <div class="item tabs tabs-secondary tabs-icon-left">
          <div  ng-app="starter" ng-controller="tasksCtrl" class="tab-item tab-main-left">
            <span class="title-red"> {{ calculateProductivity() }} </span><span class="medium-text">Productivity Ratio</span>
          </div>
          <div class="tab-item tab-main-right">
            <span class="title-red">20 </span><span class="medium-text">PMoney</span>
          </div>

        </div>

在输出中我只看到&#34; {{calculateProductivity()}}&#34;而不是结果,但如果我写tasksCollection.info它会被正确显示。 谢谢!

2 个答案:

答案 0 :(得分:1)

您计算的总数为:

total += (tasksCollection.done / tasksCollection.total);

它应该是:

total += (product.done / product.total);

答案 1 :(得分:0)

PLease see this: http://stackoverflow.com/questions/20942878/angularjs-use-a-function-in-a-controller-to-return-data-from-a-service-to-be-use

The following changes should work:

<span class="title-red"> {{ productivity_ratio }} </span><span class="medium-text">Productivity Ratio</span>

for(var i = 0; i < $scope.tasksCollection.length; i++){
        var product = $scope.tasksCollection[i];
        total += (tasksCollection.done / tasksCollection.total);
   }
$scope.productivity_ratio = total;