2016-01-30 4 views
0

Я пытаюсь суммировать общий балл на основе фильтров, предоставляемых переменными текстового поля. Я присоединяю свой javascript в конце. Есть ли у кого-нибудь предложения суммировать несколько полей в Angular?Угловая JS-фильтрация

Я интегрирую этот простой пример в больший набор столбцов, чтобы суммировать (например, 10 из них). Я думал об использовании объекта JSON для представления сумм каждого столбца, но я не уверен, как интегрировать все с более чем одним столбцом данных.

// app.js 
 
var app = angular.module('sortApp', []) 
 

 
.controller('mainController', function($scope) { 
 
    $scope.sortType  = 'fish'; // set the default sort type 
 
    $scope.sortReverse = false; // set the default sort order 
 
    $scope.searchFish = '';  // set the default search/filter term 
 
    $scope.searchName = ''; 
 
    
 
    // create the list of sushi rolls 
 
    $scope.sushi = [ 
 
    { name: 'Cali Roll', fish: 'Crab', tastiness: 2, score: 3 }, 
 
    { name: 'Philly', fish: 'Tuna', tastiness: 4, score: 2 }, 
 
    { name: 'Tiger', fish: 'Eel', tastiness: 7, score: 5 }, 
 
    { name: 'Rainbow', fish: 'Variety', tastiness: 6: score, 1 } 
 
    ]; 
 
    
 
    $scope.totalRecords = function(searchFish, searchName) { 
 
\t return $scope.sushi.reduce(function(current, record) { 
 
\t \t if(filterSushi(record, searchFish, searchName)) 
 
\t \t { 
 
\t \t \t return current + record.tastiness; 
 
\t \t } 
 
\t \t else 
 
\t \t { 
 
\t \t \t return current; 
 
\t \t } 
 
\t }, 0); 
 
    }; 
 
    
 
}); 
 

 
function filterSushi(record,searchFish, searchName) 
 
{ 
 
\t var lowName = null; 
 
\t var lowFish = null; 
 
\t if(searchName.length > 0) 
 
\t { 
 
\t \t lowName = searchName.toLowerCase(); 
 
\t } 
 
\t if(searchFish.length > 0) 
 
\t { 
 
\t \t lowFish = searchFish.toLowerCase(); 
 
\t } 
 
    var termInName = true; 
 
    var termInFish = true; 
 
\t \t \t 
 
\t if(lowName != null) 
 
\t { 
 
\t \t termInName = record.name.toLowerCase().indexOf(lowName) > -1; 
 
\t } 
 
\t if(lowFish != null) 
 
\t { 
 
\t \t termInFish = record.fish.toLowerCase().indexOf(lowFish) > -1; 
 
\t } 
 
\t return !(!termInFish || !termInName); 
 
} 
 

 
app.filter('myTableFilter', function(){ 
 
    // Just add arguments to your HTML separated by : 
 
    // And add them as parameters here, for example: 
 
    // return function(dataArray, searchTerm, argumentTwo, argumentThree) { 
 
    return function(dataArray, fish, name) { 
 
     // If no array is given, exit. 
 
     if (!dataArray) { 
 
      return; 
 
     } 
 
     // If no search term exists, return the array unfiltered. 
 
     //else if (!searchTerm) { 
 
     // return dataArray; 
 
     //} 
 
     // Otherwise, continue. 
 
     else { 
 
      var lowName = null; 
 
\t \t var lowFish = null; 
 
\t \t \t if(name.length > 0) 
 
\t \t \t { 
 
\t \t \t \t lowName = name.toLowerCase(); 
 
\t \t \t } 
 
\t \t \t if(fish.length > 0) 
 
\t \t \t { 
 
\t \t \t \t lowFish = fish.toLowerCase(); 
 
\t \t \t } 
 
      // Return the array and filter it by looking for any occurrences of the search term in each items id or name. 
 
      return dataArray.filter(function(item){ 
 
       var termInName = true; 
 
       var termInFish = true; 
 
\t \t \t 
 
\t \t \t if(lowName != null) 
 
\t \t \t { 
 
\t \t \t \t termInName = item.name.toLowerCase().indexOf(lowName) > -1; 
 
\t \t \t } 
 
\t \t \t if(lowFish != null) 
 
\t \t \t { 
 
\t \t \t \t termInFish = item.fish.toLowerCase().indexOf(lowFish) > -1; 
 
\t \t \t } 
 
       //return termInFish || termInName || termInTastiness; 
 
\t \t \t return !(!termInFish || !termInName); 
 
      }); 
 
     } 
 
    }  
 
});
<!-- index.html --> 
 

 
<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
    <meta charset="UTF-8"> 
 
    <title>Angular Sort and Filter</title> 
 

 
    <!-- CSS --> 
 
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootswatch/3.2.0/sandstone/bootstrap.min.css"> 
 
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css"> 
 
    <style> 
 
     body { padding-top:50px; } 
 
    </style> 
 

 
    <!-- JS --> 
 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
    <script src="app.js"></script> 
 

 
</head> 
 
<body> 
 
<div class="container" ng-app="sortApp" ng-controller="mainController"> 
 
    
 
    <div class="alert alert-info"> 
 
    <p>Sort Type: {{ sortType }}</p> 
 
    <p>Sort Reverse: {{ sortReverse }}</p> 
 
    <p>Search Query: {{ searchFish }}</p> 
 
    </div> 
 
    
 
    <form> 
 
    <div class="form-group"> 
 
     <div class="input-group"> 
 
     <div class="input-group-addon"><i class="fa fa-search"></i></div> 
 

 
     <input type="text" class="form-control" placeholder="Search da Fish" ng-model="searchFish"> 
 
     <input type="text" class="form-control" placeholder="Search da Name" ng-model="searchName"> 
 

 
     </div>  
 
    </div> 
 
    </form> 
 
    
 
    <table class="table table-bordered table-striped"> 
 
    
 
    <thead> 
 
\t <tr> 
 
     <td> 
 
      <a href="#" ng-click="sortType = 'name'"> 
 
      Sushi Roll 
 
      <span ng-show="sortType == 'name'" class="fa fa-caret-down"></span> 
 
      </a> 
 
     </td> 
 
     <td> 
 
      <a href="#" ng-click="sortType = 'fish'; sortReverse = !sortReverse"> 
 
      <span ng-show="sortType == 'fish'" class="fa fa-caret-down"></span> 
 
      Fish Type 
 
      </a> 
 
     </td> 
 
     <td> 
 
      <a href="#" ng-click="sortType = 'tastiness'"> 
 
      <span ng-show="sortType == 'tastiness'" class="fa fa-caret-down"></span> 
 
      Taste Level 
 
      </a> 
 
     </td> 
 
     <td> 
 
      Score 
 
     </td> 
 
\t \t </tr> 
 
    </thead> 
 
    
 
    <tbody> 
 
     <tr ng-repeat="roll in sushi| orderBy:sortType:sortReverse | myTableFilter:searchFish:searchName"> 
 
     <td>{{ roll.name }}</td> 
 
     <td>{{ roll.fish }}</td> 
 
     <td>{{ roll.tastiness }}</td> 
 
\t \t <td>{{ roll.score}}</td> 
 
     </tr> 
 
\t <tr><td></td><td></td><td>total: {{totalRecords(searchFish,searchName);}}</td><td>TotalScore: ??</td></tr> 
 
    </tbody> 
 
    
 
    </table> 
 
    
 
</div> 
 
</body> 
 
</html>

ответ

0

В новых версиях Угловая у вас есть доступ к псевдониму фильтрованного массива в ng-repeat с помощью as myFilteredArray.

Вы можете использовать это, чтобы сделать ваши суммы

<tr ng-repeat="roll in sushi| filter1 | filter2 | filter3 as filteredFish"> 

Total: {{totalRecords()}} 

контроллер

$scope.totalRecords = function() { 
    if(!$scope.filteredFish){ 
     return 0; 
    } 
    return $scope.filteredFish.reduce(function(current, record) { 
     return current + record.tastiness; 
    }, 0); 
}; 

Обратите внимание, что версия аф Угловая показано на вопрос не поддерживает as

DEMO