如何处理用于角度指令的额外标记?

时间:2014-09-05 05:35:30

标签: angularjs angularjs-directive

我有两个指令:appButtonGroupappGroupedButton。我的css期望<app-grouped-button>元素是<app-button-group>的直接后代,因此它们可以作为flexbox项目布局。但我希望将appGroupedButton元素转换为按钮组,但会在分组按钮周围添加<ng-transclude>元素。

解决这个问题的一种方法是将<ng-transclude>元素设置为flex容器,但这意味着我的css知道&#39;关于transclude元素,我将其视为实现细节。我已经尝试将该指令用作评论,但由于某些原因不起作用,并且在文档中不鼓励评论指令。

解决这个问题的好方法是什么?

这是指令的javascript代码:

Navigation.directive('appButtonGroup', function(){
  return {
    restrict: "EA",
    transclude: true,
    controller: function($scope, $location){
      var buttons = $scope.buttons = [];
      console.log("initialized button group controller");

      this.addButton = $scope.addButton = function(button){
        if (buttons.length === 0){
          button.active = true;
        }
        buttons.push(button);
      }

      this.select = $scope.select = function(button){
        angular.forEach(buttons, function(){
          button.active = false;
        });
        button.active = true;
        $location.path(button.hrf);
      }
    },
    template: "<ng-transclude></ng-transclude>"
  }
})
.directive('appGroupedButton', function(){
      return {
        restrict: "EA",
        transclude: true,
        require: '^appButtonGroup',
        scope: {href: '@'},
        link: function(scope, element, attrs, BGCtrl){
          console.log(BGCtrl);
          BGCtrl.addButton(scope);
          console.log("linking button "+scope);
        },
        template: "<div ng-class=active ? \'active\' : \'\''>" +
                  "<ng-transclude></ng-transclude>" +
                  "</div>"
      }
});

这是按钮组的标记:

<app-button-group>
    <app-grouped-button>Podcasts</app-grouped-button>
    <app-grouped-button>Playlists</app-grouped-button>
    <app-grouped-button>Downloading</app-grouped-button>
    <app-grouped-button>Discover</app-grouped-button>
</app-button-group>

因此问题在于,转换会在<app-grouped-button>元素周围添加一个额外的元素,这会导致问题,因为我希望将app-button-group用作flexbox容器。

2 个答案:

答案 0 :(得分:1)

您可以使用 transclude function 来获取已转化的内容,并将其直接附加到<app-button-group>元素:

app.directive('appButtonGroup', function () {
  return {
    restrict: 'E',
    transclude: true,
    template: '<h4>This is a button-group:</h4>',
    link: function (scope, elem, attrs, ctrl, $transclude) {
      $transclude(function (content) { elem.append(content); });
    }
  };
});

另请参阅此 short demo

答案 1 :(得分:0)

转换时不需要

ng-transclude,您也可以使用transclude函数。可能有所帮助:

$transclude(scope,function(clone){
   ...
});