2014-11-04 138 views
2

如何創建自定義過濾器angularjs的JavaScript控制器端? 我想在陣列稱爲段由SegmentId搜索,來創建濾波器那些由SegmentId上段數組搜索FOREACH -如何創建自定義過濾器angularjs javascript控制器端?

//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; 
} 

});

+0

請張貼一個例子模型(即'$ scope.segments') – boindiil 2014-11-04 15:21:48

+0

你想創建一個過濾器把邏輯控制器我不明白?那麼你不需要一個過濾器,你可以直接在控制器中進行過濾,過濾器用於過濾顯示在HTML – Charlie 2014-11-04 15:22:56

+0

@boindiil [{「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歡迎回來」}] – 2014-11-04 15:31:23

回答

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>

+0

非常感謝!工作很好,我有另一個問題,加載模塊到控制器的順序。這意味着$過濾器假設爲$ scope後面的第二個 – 2014-11-05 09:08:28

+0

請看一看[this link](http://thegreenpizza.github.io/2013/05/25/building-minification-safe-angular.js-applications/) – boindiil 2014-11-05 13:14:05

+0

@boindiil如何使用$ filter實現'SegmentId!== segmentId'? – 2015-08-25 13:15:41

1

只需要在你的控制器中添加過濾器的依賴,然後調用它。

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

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

}]); 
相關問題