如何在角度js中获取控制器中的自定义过滤器值

时间:2017-07-11 08:36:02

标签: angularjs

 mainApp.filter('sumOfValue', function() {
    return function(data, key) {
      debugger;
      if (angular.isUndefined(data) || angular.isUndefined(key))
        return 0;
      var sum = 0;

      angular.forEach(data, function(v, k) {
        sum = sum + parseFloat(v[key]);
      });
      return sum;
    }
});

这是我的filter.js。以及如何在sumofvalue中获取存储在控制器中的值。任何人帮助我。enter code here

1 个答案:

答案 0 :(得分:0)

您可以将此滤镜用作角度js中的预定义滤镜 这是演示链接Jsfiddle

<强>的js

var app = angular.module('myApp', []);

app.controller('ctrl', function($scope) {
  $scope.data = [{
    id: 1,
    value: 'abc'
  }, {
    id: 1,
    value: 'test'
  }];
});

app.filter('sumOfValue', function() {
  return function(data, key) {
    if (key)
      return data.filter(function(obj) {
        return obj.value == key;
      });
    return data;
  }
});

app.run(function() {

});

<强> HTML

<div ng-app='myApp'>
  <div ng-controller='ctrl'>
    <input type='text' ng-model='search' placeholder='search'>
    <br>
    <span ng-repeat='item in data| sumOfValue: search'>
      {{item.value}}
    </span>
  </div>
</div>

这可能会对你有帮助。