AngularJS条件指令

时间:2013-12-23 09:26:39

标签: javascript angularjs

我有以下指令:

myDirective.directive('sidebar', function () {
  return {
    restrict: 'E',
    replace: true,
    template: '<li ng-repeat="m in menu"><a href="{{m.url}}"><i class="{{m.image}}"></i> {{m.name}}</a></li>',
    link: function (scope, elem, attrs) {
      scope.menu = [
        {
          "name": "Home",
          "url": "/",
          "image": "fa fa-bar-chart-o"
        },
        {
          "name": "Data Integration",
          "url": "/manage/dataintegration/index",
          "image": "fa fa-dashboard"
        },
        {
          "name": "Users",
          "url": "/manage/users/index",
          "image": "fa fa-dashboard"
        },
        {
          "name": "Logger",
          "url": "/manage/logger/index",
          "image": "fa fa-dashboard"
        },
        {
          "name": "Drop",
          "url": "",
          "image": "fa fa-dashboard",
          "submenu": [
            {
              "name": "Logger",
              "url": "/manage/logger/index",
              "image": "fa fa-dashboard"
            },
            {
              "name": "Logger2",
              "url": "/manage/logger/index",
              "image": "fa fa-dashboard"
            }
          ]
        }
      ]

    }
  }
});

是否有可能以某种方式在模板中应用ng-if,以便我能够知道当前菜单项是否具有submenu元素,从而相应地更改模板?

1 个答案:

答案 0 :(得分:0)

模板中的

template: '<li ng-repeat="m in menu">' + 
            '<a href="{{m.url}}"><i class="{{m.image}}"></i> {{m.name}}</a>' +
            '<ul ng-if="m.submenu">' +
               '<li ng-repeat="sm in m.submenu">' +
                '<a href="{{sm.url}}"><i class="{{sm.image}}"></i> {{sm.name}}</a>' +
               '</li>' +
            '</ul>' +
           '</li>',

没有尝试过以上。可能需要一些调整。