如何在AngularJS中找到长度

时间:2018-05-21 12:31:48

标签: html angularjs

var app = angular.module('myApp', []);
app.controller('myctrl', function ($scope) {

    $scope.friends = [
      { name: "Peter", age: 20 },
      { name: "Pablo", age: 55 },
      { name: "Linda", age: 20 },
      { name: "Marta", age: 37 },
      { name: "Othello", age: 20 },
      { name: "Markus", age: 32 }
    ];

});

年龄:20我想找到那些人的数量。我使用了 ng-if ,但我所做的是总是找到索引的长度。你能帮忙吗?

我还有一个问题。我们想把长度写入数据徽章。 <ul ng-if="result.type=='mesh'" class="mdl-list__item-primary-content mdl-badge results-icon" data-badge={{len}}>

我写了,但事实并非如此。

2 个答案:

答案 0 :(得分:1)

使用数组的过滤方法。我添加了代码段。

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('myctrl', function ($scope) {

    $scope.friends = [
      { name: "Peter", age: 20 },
      { name: "Pablo", age: 55 },
      { name: "Linda", age: 20 },
      { name: "Marta", age: 37 },
      { name: "Othello", age: 20 },
      { name: "Markus", age: 32 }
    ];
    
    var len = $scope.friends.filter(function(friend){
       if( friend.age == 20 ){
           return friend;
       }
    }).length;
    
    console.log("length=" + len);

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myctrl"></div>
&#13;
&#13;
&#13;

这是一种使用{j}中存在$filter服务的更好方法。

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('myctrl', function ($scope, $filter) {

    $scope.friends = [
      { name: "Peter", age: 20 },
      { name: "Pablo", age: 55 },
      { name: "Linda", age: 20 },
      { name: "Marta", age: 37 },
      { name: "Othello", age: 20 },
      { name: "Markus", age: 32 }
    ];
    
    var len = $filter('filter')($scope.friends, {'age' : 20}).length;
    
    console.log("length=" + len);

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myctrl">
&#13;
&#13;
&#13;

答案 1 :(得分:1)

听起来你需要过滤器。您可以通过许多不同的方式将其应用于输入。这是一个例子,带有一个复选框和一个设定值,例如{'age':20},您也可以动态更改:

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
  $scope.age = 20;
  $scope.c = true;
  $scope.friends = [
    { name: "Peter", age: 20 },
    { name: "Pablo", age: 55 },
    { name: "Linda", age: 20 },
    { name: "Marta", age: 37 },
    { name: "Othello", age: 20 },
    { name: "Markus", age: 32 }
  ];

});
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myctrl">

    <input type="checkbox" ng-model="c" /> <tt>age:{{age}}</tt>
    <br>
    <input type="range" name="range" ng-model="age" min="0" max="100">
    <hr>

    <div ng-repeat="f in filtered=(friends | filter: c ? {'age':age} : '')">
      {{f}}
    </div>
    <hr>
    Length: {{filtered.length}}

  </div>
</body>

</html>
&#13;
&#13;
&#13;