1

我的目标是创建一个可以与 Twitter Bootstrap 一起使用的导航项指令。我当前的代码将<li>标签进一步降低了一个级别,所以我认为这就是 bootstrap 的 CSS 不兼容的原因。

这是我的directions.js 文件

angular.module('wdiary.directives', [])
 .directive('navitem', [function(){
    return {
        restrict: 'E',
        transclude: true,
        templateUrl: 'partials/directives/navitem.html',
        scope: {} ,
        link: function(scope, element, attrs) {
            scope.redirectRoute = attrs.redirect;
            var r = attrs.redirect;
            scope.itemName = r.substring(r.indexOf('/') + 1, r.length);
        }
    }
 }]);

navitem.html 指令模板:

<li ng-class = "{active: $route.current.activeNavigationItem == '{{itemName}}'}"><a href="{{ redirectRoute }}" ng-transclude> </a></li>

index.html 的一部分:

<div class="navbar" ng-controller = "NavigationController">
  <div class="navbar-inner">
    <a class="brand" href="#/">WDiary</a>
    <ul class="nav">
      <navitem redirect = "#/write"> Write </navitem>
      <navitem redirect = "#/list"> List </navitem>
    </ul>

  </div>
</div>

和 controllers.js 文件

angular.module('wdiary.controllers', [])    
.controller('NavigationController', ['$scope', '$route', function($scope, $route) {
    $scope.$route = $route;
}])

我检查了结果,这是我可以看到的:

<ul class="nav">
  <navitem redirect="#/write" class="ng-isolate-scope ng-scope">
    <li ng-class="{active: $route.current.activeNavigationItem == 'write'}">
        <a href="#/write" ng-transclude=""> 
            <span class="ng-scope"> Write </span>
        </a>
    </li>
  </navitem>
</ul>

我认为解决方案是告诉 Angular 不要将列表包装在另一个标签中?

4

1 回答 1

4

将 replace: true 添加到指令中的返回对象。这将像您想要的那样替换它。

angular.module('wdiary.directives', [])
 .directive('navitem', [function(){
    return {
        replace: true,
        restrict: 'E',
        transclude: true,
        templateUrl: 'partials/directives/navitem.html',
        scope: {} ,
        link: function(scope, element, attrs) {
            scope.redirectRoute = attrs.redirect;
            var r = attrs.redirect;
            scope.itemName = r.substring(r.indexOf('/') + 1, r.length);
        }
    }
 }]);
于 2013-06-17T18:32:25.323 回答