如何对指令输出进行排序?

时间:2013-12-02 16:04:12

标签: angularjs angularjs-directive

我有以下指令:

app.directive('sidebar', function () {
  return {
    restrict: 'E',
    replace: true,
    template: '<li ng-repeat="(keymenu, valmenu) in menu"><a href="{{valmenu.url}}"><i class="{{valmenu.image}}"></i><span class="hidden-sm">{{keymenu}}</span></a></li>',
    link: function (scope, elem, attrs) {
      scope.menu = {
        "Home": {
          "sort": 1,
          "url": "/",
          "image": "fa fa-bar-chart-o"
        },
        "Datasources": {
          "sort": 2,
          "url": "/datasources",
          "image": "fa fa-dashboard"
        },
        "Logger": {
          "sort": 3,
          "url": "/Logger",
          "image": "fa fa-dashboard"
        }

      }
    }
  }
});

目前订单为:Datasources, Home, Logger我想通过sort媒体资源或其自然资源订购。scope.menu订单,因为元素在{{1}}对象中排序。

1 个答案:

答案 0 :(得分:2)

您可以orderBy直接使用<li />模板:

此代码将为您想要的属性名称排序菜单:

'<li ng-repeat="(keymenu, valmenu) in menu| orderBy:myProperty">'

编辑:

您应该更改JSON的外观,否则您将无法访问和订购菜单。每个菜单项的方式都是不同的对象,你应该这样做:

scope.menu =[
   {
      "name": "Home",
      "sort": 1,
      "url": "/",
      "image": "fa fa-bar-chart-o"
    },
    {
      "name":"Datasources",
      "sort": 2,
      "url": "/datasources",
      "image": "fa fa-dashboard"
    },
    {
      "name": "Logger",
      "sort": 3,
      "url": "/Logger",
      "image": "fa fa-dashboard"
    }
  ]

然后按name排序,例如:

'<li ng-repeat="(keymenu, valmenu) in menu| orderBy:name">'