指令搞砸了造型,AngularJS

时间:2013-06-17 18:29:25

标签: javascript angularjs angularjs-directive

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

这是我的directives.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不要将列表包装在另一个标签中吗?

1 个答案:

答案 0 :(得分: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);
        }
    }
 }]);