【问题标题】:Populate table from JSON with search使用搜索从 JSON 填充表
【发布时间】:2015-04-28 08:51:18
【问题描述】:

我能够从 JSON 对象纯粹实现网格 - AngularJS ng-repeat to populate grid from array。但是,由于添加索引的性质,无法使用 ng-modelfilter:search 创建搜索栏 - 它只能搜索每个表格行中的第一个。

var test= angular.module("app", []);

test.controller("appControl", function($scope, $http) {
	$http.get("http://www.w3schools.com/angular/customers.php")
		.success(function (response) {
			$scope.data = response.records;
		}
	);
    $scope.getFiltered= function(obj, idx){
       //Set a property on the item being repeated with its actual index
       //return true only for every 1st item in 5 items
       return !((obj._index = idx) % 5);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<body ng-app='app' ng-controller='appControl'>
    <input type='text' ng-model='search.Country' />
    <table>
        <tr ng-repeat="work in data | filter:getFiltered | filter:search">
            <td>{{work.Country}}</td>
            <td>{{data[work._index+1].Country}}</td>
            <td>{{data[work._index+2].Country}}</td>
            <td>{{data[work._index+3].Country}}</td>
            <td>{{data[work._index+4].Country}}</td>
        </tr>
    </table>
</body>

data 的长度可能会或不会使表格看起来像一个完美的矩形。

我正在制作一个函数来拆分数组并在 JavaScript 本身中创建网格,但我仍然不确定如何通过搜索输入过滤它。

第二次尝试(使用提到的功能,但还没有过滤器......):

var test= angular.module("app", []);

function createGrid(arr, width) {
    newArr = [];
    reps = Math.ceil(arr.length/width) * width;
    k = 0;
    for (var i = 0; i < reps/width; i++) {
        newArr[i] = [];
    }
    
    for (var i = 0; i < reps/width; i++) {
        for (var j = 0; j < width; j++) {
            (arr[k]) ? newArr[i][j] = arr[k] : newArr[i][j] = "";
            //console.log(i, j, arr[k]);
            k++;
        }
    }
    
    return newArr;
}

test.controller("appControl", function($scope, $http) {
    $scope.gridWidth = 4;
	$http.get("http://www.w3schools.com/angular/customers.php")
		.success(function (response) {
			$scope.data = createGrid(Object.keys(response.records).map(function(k) { return response.records[k] }), $scope.gridWidth);
		}
	);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<body ng-app='app' ng-controller='appControl'>
    <input type='text' ng-model='search.Country' />
    <table>
        <tr ng-repeat="row in data">
            <td ng-repeat='work in row'>
                {{ work.Country }}
            </td>
        </tr>
    </table>
</body>

【问题讨论】:

    标签: javascript html json angularjs angularjs-ng-repeat


    【解决方案1】:

    你可以试试这样的:

    var test= angular.module("app", []);
      
    test.controller("appControl", function($scope, $http) {
    
    	$http.get("http://www.w3schools.com/angular/customers.php")
    		.success(function (response) {
    	         $scope.data = response.records;
                     $scope.filteredData= response.records;
    		}
    	);
    
         $scope.$watch('search', function () {
    
          var array=[];
          for(var i in $scope.data)
          {
              if($scope.search==undefined || $scope.search.length == 0 ||  ($scope.data[i].Country!=undefined&&$scope.data[i].Country.toUpperCase().startsWith($scope.search.toUpperCase()))){
                 array.push($scope.data[i]);
              }
          }
          $scope.filteredData=array;
        });
    
        $scope.getFiltered= function(obj, idx){
           //Set a property on the item being repeated with its actual index
           //return true only for every 1st item in 3 items
           return !((obj._index = idx) % 5);
        }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <body ng-app='app' ng-controller='appControl'>
        <input type='text' ng-model='search' />
        <table>
            <tr ng-repeat="work in filteredData | filter:getFiltered | filter:search">
                <td>{{work.Country}}</td>
                <td ng-show="filteredData[work._index+1]">{{filteredData[work._index+1].Country}}</td>
                <td ng-show="filteredData[work._index+2]">{{filteredData[work._index+2].Country}}</td>
                <td ng-show="filteredData[work._index+3]">{{filteredData[work._index+3].Country}}</td>
                <td ng-show="filteredData[work._index+4]">{{filteredData[work._index+4].Country}}</td>
            </tr>
        </table>
    </body>

    【讨论】:

    • 问题是我只想要搜索结果,而不是整行 (prntscr.com/6yyra2)
    • 更新了我的答案,现在试试这个。让我知道是否有帮助。
    • 谢谢!我接受了它并稍作改动 - 我用包含()替换了startsWith()。
    • 这个答案仍然存在一些缺陷,例如不需要过滤器:搜索。也不应该针对undefined 而是针对typeof 'undefined' 等来检查是否存在未定义的变量。看起来你只是复制了我的部分答案而没有理解它们:(
    • 他的回答实际上是第一个,对不起。此外,您的问题有一些问题,而这个问题没有 - 但是,我确实赞成您的问题,因为我只能接受一个答案。
    【解决方案2】:

    您可以在成功的 Ajax 调用之后以及每次您的模型 search 更改时对项目进行预过滤。

    1. 将之前过滤的项目保存到$scope.workers
    2. 使用$scope.$watch观察模型的变化search
    3. 使用函数searched(data) 过滤具有使用indexOf 方法在搜索字段中给出的字符的条目。如果过滤器为空,则还显示每个项目 (typeof $scope.search == 'undefined')。
    4. 如果您希望搜索不区分大小写,请在使用.indexOf() 时转换search 和国家/地区.toLowerCase()

    那么您将只需要一个 Angular 过滤器$scope.getFiltered(),它可以确保条目为五行。

    var test= angular.module("app", []);
    
    test.controller("appControl", function($scope, $http) {
    	$http.get("http://www.w3schools.com/angular/customers.php")
    		.success(function (response) {
    			$scope.data = response.records;
                $scope.workers = $scope.searched($scope.data);
    		}
    	);
    
        $scope.getFiltered= function(obj, idx){
           //Set a property on the item being repeated with its actual index
           //return true only for every 1st item in 5 items
           return !((obj._index = idx) % 5);
        };
      
        $scope.searched = function (data) {
          var array = [];
          var max = 0;
          
          if (typeof data === 'object') {
            max = data.length;
          }
          
          for (var i = 0; i < max; i += 1) {
            if (typeof $scope.search == 'undefined' || data[i].Country.toLowerCase().indexOf($scope.search.toLowerCase()) != -1) {
              array.push(data[i]);
            }
          }
          
          return array;
        
        };
    
        $scope.$watch('search', function () {
          $scope.workers = $scope.searched($scope.data);
        })
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <body ng-app='app' ng-controller='appControl'>
        <input type='text' ng-model='search' />
        <table>
            <tr ng-repeat="work in workers | filter:getFiltered">
                <td>{{ work.Country }}</td>
                <td>{{ workers[$index+1].Country }}</td>
                <td>{{ workers[$index+2].Country }}</td>
                <td>{{ workers[$index+3].Country }}</td>
                <td>{{ workers[$index+4].Country }}</td>
            </tr>
        </table>
    </body>

    【讨论】:

    • 是否可以不让搜索区分大小写?
    • 非常感谢您的回答和解释:)
    猜你喜欢
    • 2014-07-12
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 2018-10-14
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多