angularjsangularjs-orderby

How to orderBy a value returned after function call which is in loop?


I am looping an object in view and calling a function which takes its members as parameters.

The function returns me a value every time the function is called.

I want to orderBy that returned value.

But my problem is, that value is returned after function call and I cannot store the values in an array so that I can sort.

    <div ng-repeat="member in current_project.members | orderBy : '?'"> 
     <span class="taskCompletionEst">
       Estimated time: 
             {{estimatedTimeSum(selected_date, member.id)}} hrs
     </span>

Controller

      $scope.estimatedTimeSum = function(date, member_id) {
       sum = 0
       angular.forEach($scope.projects[0].tasks[date], function(task, 
       projectname) {
        angular.forEach(task, function(value, key) {
         if (value["user_id"] == member_id) {
          if (value["completion"] != undefined) {
           sum += parseInt(value["estimation"])
          } 
         else {
          sum += parseInt(value["estimated_time"])
         }
        }
      });
    });
  return sum
 }

I need to orderBy Estimated time sum.


Solution

  • You should wrap your estimatedTimeSum function into intermediate sort function, which will be passed to orderBy filter:

    angular.module('app', []).controller('ctrl', function($scope) {
      $scope.current_project = {
        members: [{
          id: 10
        }, {
          id: 250
        }, {
          id: 300
        }, {
          id: 150
        }, {
          id: 70
        }, {
          id: 800
        }]
      }; 
    
      $scope.sort = function(date) {
        return function(member){            
          return $scope.estimatedTimeSum(date, member.id);
        }    
      }
    
      $scope.estimatedTimeSum = function(date, member_id) {
        //only to  stub
        return member_id % (date || 1);
      }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app='app' ng-controller='ctrl'>
      <input type='number' ng-model='selected_date' ng-init='selected_date = 11'/>
      <div ng-repeat="member in current_project.members | orderBy : sort(selected_date)">
        <span class="taskCompletionEst">
           {{member.id}} Estimated time: {{estimatedTimeSum(selected_date, member.id)}} hrs
         </span>
      </div>
    </div>