在AngularJS中抽象过滤器`orderBy`函数

时间:2018-01-14 14:11:05

标签: arrays angularjs angularjs-filter

因此,为了尽可能保持我们的代码清洁,并且我假设要防止污染全局命名空间,我必须将我的ctrls函数抽象为单独的文件,但是我无法抽象一个特殊功能,它按照从CSV阵列接收的颜色来命令我的小部件,红色先行,琥珀色等等。

需要抽象的功能

Sub delelete_folder()

Dim folder As Object
Dim path As String
path = ("E:\New folder\targetfolder")
Set folder = CreateObject("scripting.filesystemobject")

    folder.deletefolder path, True

End Sub

HTML

$scope.colourOrder = function (x) {
    switch (x.colour) {
        case "Red":
            return 1;
            break;
        case "Amber":
            return 2;
            break;
        case "Green":
            return 3;
            break;
    };

所以目前这在html的相关ctrl中运行得非常好,我只是不知道如何抽象这个函数,然后将其调回Ctrl。

任何有关此流程如何运作的解释的帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

创建custom filter

app.filter("orderByColour",function() {
    return function(xArray) {
        return xArray.sort((a,b) => colourOrder(a)-colourOrder(b));
    };
    function colourOrder(x) {
        switch (x.colour) {
            case "Red":
                return 1;
                break;
            case "Amber":
                return 2;
                break;
            case "Green":
                return 3;
                break;
            default:
                return 0;
        };
    }
})

用法:

<table>
  <tr ng-repeat="x in friends | orderByColour">
    <td>{{x.name}}</td>
    <td>{{x.phone}}</td>
    <td>{{x.colour}}</td>
  </tr>
</table>

The DEMO

&#13;
&#13;
angular.module("app",[])
.controller("ctrl", function($scope) {
    $scope.friends = [
        {name: 'John',   phone: '555-1212',  colour: 'Red'},
        {name: 'Mary',   phone: '555-9876',  colour: 'Green'},
        {name: 'Mike',   phone: '555-4321',  colour: 'Amber'},
        {name: 'Adam',   phone: '555-5678',  colour: 'Blue'},
        {name: 'Julie',  phone: '555-8765',  colour: 'Green'},
    ];
})
.filter("orderByColour",function() {
    return function(xArray) {
        return xArray.sort((a,b) => colourOrder(a)-colourOrder(b));
    };
    function colourOrder(x) {
        switch (x.colour) {
            case "Red":
                return 1;
                break;
            case "Amber":
                return 2;
                break;
            case "Green":
                return 3;
                break;
            default:
                return 0;
        };
    }
})
&#13;
  <script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app" ng-controller="ctrl">
    <table>
      <tr ng-repeat="x in friends | orderByColour">
        <td>{{x.name}}</td>
        <td>{{x.phone}}</td>
        <td>{{x.colour}}</td>
      </tr>
    </table>
  </body>
&#13;
&#13;
&#13;