1

我正在尝试创建一个指令,该指令可以将两件事转换到不同的位置,其中一个是ng-repeat,但是在我的编译函数中使用$transclude break if return undefined is not a function,但是如果我这样做它pre-compile可以工作但ng-repeat没有内容。

我的代码看起来像这样

 .directive('sidebarItem', ['_', function(_) {
    return {
      replace: true,
      transclude: true,
      scope: {
        title: '@',
        state: '@',
        activeState: '=',
        dropdown: '='
      },
      compile: function(ele, attrs, transclude) {
        transclude(ele) // This returns error
        return {
          pre: function(scope, ele,attrs, ctrl, trns) {
            trns(scope) // This has my transcluded content but the ng-repeat is empty
          }
        }
      }
    }
  }

我也尝试过手动转换,它返回一个空的 ng-repeat

trns(scope.$parent, function(tEle, tScope) {
  var repeat = tEle[1].querySelector('[repeat]'),
  newEle = angular.element('<li ng-repeat="item in studentDropdown"></li>'),
 dropdown = ele[0].querySelector('.dropdown')

  tScope.studentDropdown // Can access here
  newEle.append(repeat.innerHTML)
  angular.injector(['ng']).get('$compile')(newEle) // returns ng-repeat comment but no items
  angular.element(dropdown).append(newEle)
})

侧边栏项目的模板

li.sidebar-item(ng-class='{active: active, dropdown: dropdown, "dropdown-open": isDropdownOpen}')
  .sidebar-content
    a.sidebar-item-link(ng-if='!dropdown' ui-sref='{{state}}')
    a.sidebar-item-link(ng-if='dropdown' ng-click='toggleDropdown()')
    .icon(ng-transclude)

    .title {{ title }}

    .down-arrow(ng-if='dropdown')

  ul.dropdown(ng-if='dropdown')

指令的使用

sidebar-item
  div(has-dropdown)
    div(icon)
      //icon stuff
    div(dropdown)
      li(ng-repeat='item in dropdown')
        | {{ item }}

交替使用

 sidebar-item
  div(has-dropdown)
    div(icon)
      //icon stuff
    div(dropdown)
      li Item 1
      li Item 2
4

0 回答 0