如何创建自定义过滤器angularjs javascript控制器端?

时间:2014-11-04 15:11:44

标签: javascript html angularjs angularjs-filter

如何创建自定义过滤器angularjs javascript控制器端? 我想通过SegmentId搜索名为segment的数组,以创建过滤器,通过SegmentId进行段数组搜索 -

    //Controller

    $scope.GetSegmentDetails = function (id) {
        $scope.SegmentName = $filter('SegmentById')($scope.segments,id);
    }


    //Filter
    app.filter('SegmentById', function () {
        return function (input, searchPerson) {
        if (!searchPerson)
            return input;

        var results = [];
        angular.forEach(input, function (person) {
        }
    });

    return results;
}

});

2 个答案:

答案 0 :(得分:4)

您不必编写一个过滤器来按SegmentId过滤。这里有一个例子



function MyCtrl($scope, $filter) {
  $scope.data = [{"SegmentId":"1","Description":"hod Registrations"}, {"SegmentId":"2","Description":"hod Inactive"}, {"SegmentId":"3","Description":"hod testUpd"}, {"SegmentId":"8","Description":"hod test"}, {"SegmentId":"1111","Description":"hod Release"}, {"SegmentId":"12","Description":"hod Requests"}, {"SegmentId":"13","Description":"hod Welcome Back"}]
  
  $scope.filterData = function(segmentId) {
    return $filter('filter')($scope.data, { SegmentId: segmentId });
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="MyCtrl">
  Full:
  <ul>
    <li ng-repeat="Segment in data">
      {{Segment.SegmentId}}
    </li>
  </ul>
  Filtered in View:
  <ul>
    <li ng-repeat="Segment in data | filter:{SegmentId:1111}">
      {{Segment.SegmentId}}
    </li>
  </ul>
  Filtered in Controller:
  <ul>
    <li ng-repeat="Segment in filterData(1111)">
      {{Segment.SegmentId}}
    </li>
  </ul>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

只需要在控制器中添加过滤依赖项,然后再调用它。

app.controller("YourController", ['$scope', '$filter', function ($scope, $filter){

$filter('filterName')($args));

}]);