Angular只从数组中获取所需的数据

Angular get only required data from array

本文关键字:数据 获取 数组 Angular      更新时间:2023-09-26

我有一个ng重复,它可以获取所有数据,但我只需要来自所提供的源的某些数据

HTML

<tr ng-repeat="val in values ">
    <td ng-bind="$index"></td>
    <td ng-bind="val.rec">ED1500322</td> 
    <td>working</td>
    <td ng-bind="val.result">I am going to School</td>
    <td>
      <div class="radio">
        <input ng-model="val.iscorrect" value="yes" type="radio">
        <label for="opt1">yes</label>
        <input ng-model="val.iscorrect" value="no" type="radio">
        <label for="opt10">no</label>
      </div>
    </td>
  </tr>

数据

$scope.values = [{
    name: "John",
    rec:234,
    iscorrect: ''
  }, {
    name: "Paul",
    rec:44,
    iscorrect: ''
  }, {
    name: "George",
    rec:2664,
    iscorrect: 'no'
  }, {
    name: "Ringo",
    rec:124,
    iscorrect: 'yes'
  }];

我们可以看到我有某些值,其中iscorrect="。我只希望相应的值在我的$scope.values和html 中

plunkerhttp://plnkr.co/edit/f0l7MHN7UAvOLNZ8BCjV?p=preview

感谢您在获取iscorrect="的数据方面提供的任何帮助。。。

所以你只想显示那些iscorrect=''的地方?

试试这个:

<tr ng-repeat="val in values" ng-if="!val.iscorrect">

修改了答案,将其从过滤器中删除,并使用ng if,后者更清洁plnkr

ng-repeat中使用以下内容来过滤值

<tr ng-repeat="val in getValues(values) ">
  <td ng-bind="$index"></td>
  <td ng-bind="val.rec">ED1500322</td> 
  <td>working</td>
  <td ng-bind="val.result">I am going to School</td>
  <td>
   <div class="radio">
    <input ng-model="val.iscorrect" value="yes" type="radio">
    <label for="opt1">yes</label>
    <input ng-model="val.iscorrect" value="no" type="radio">
    <label for="opt10">no</label>
   </div>
  </td>
</tr>

然后在控制器中:

$scope.getValues = function (values) {
  return values.filter(function (item) {
    return item.iscorrect === '';
  });
}

我建议不要使用过滤器,因为它们添加了很多观察者并触发摘要周期,这对UI性能不利

更新:添加plunkr链接:http://plnkr.co/edit/3GJZca8YLnW4P0BGulfq?p=preview

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myController">
  <div ng-repeat="val in values | filter : val.iscorrect='no'">
    <input ng-model="val.iscorrect" value="yes" type="radio">
    <label for="opt1">yes</label>
    <input ng-model="val.iscorrect" value="no" type="radio">
    <label for="opt10">no</label>
  </div>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myController", function($scope) {
  $scope.values = [{
    name: "John",
    rec: 234,
    iscorrect: 'no'
  }, {
    name: "Paul",
    rec: 44,
    iscorrect: 'yes'
  }, {
    name: "George",
    rec: 2664,
    iscorrect: 'no'
  }, {
    name: "Ringo",
    rec: 124,
    iscorrect: 'yes'
  }];
});
</script>
</body>
</html>