2

Angular 新手。尝试创建一个可重用的指令,以便我可以跨页面共享导航标题栏。每个单独的 html 页面应该能够指定当前或活动页面是什么,因此应用 css 属性来区分该页面。

所有逻辑都应包含在指令中,以便使用此导航栏的每个 html 页面只需要设置 ActivePage 的“属性”。

但是,我似乎无法在模板中获得条件 ng-class 来应用 CSS 类。有人可以帮我发现我的问题吗?

Plunker 示例:http: //plnkr.co/edit/JTI8wLOhN5xWeDdD9i2l

正在使用:

  <section ng-app="NavBarApp" ng-controller="NavBarCtrl">
    <nav-Bar ActivePage="{{Pages.Navigation.Page2}}"></nav-Bar>
  </section>

Javascript:

var Pages = {};
Pages.Navigation = {};

Pages.Navigation.Page1 = {
  Name: "Page 1",
  BaseLink: "Page1.html"
};
Pages.Navigation.Page2 = {
  Name: "Page 2",
  BaseLink: "Page2.html"
};
Pages.Navigation.Page3 = {
  Name: "Page 3",
  BaseLink: "Page3.html"
};

var NavBarApp = angular.module('NavBarApp', []);

NavBarApp.controller('NavBarCtrl', function NavBarCtrl($scope){
  $scope.Pages = {};
  $scope.Pages.Navigation = Pages.Navigation;
});

NavBarApp.directive('navBar', function(){
  return {
  restrict: 'E',
  replace: true,
  scope: {
    strActivePage: "@ActivePage"
  },
  controller: function($scope){
    $scope.aryPagesList = [];
    for(var strProp in Pages.Navigation){
      $scope.aryPagesList.push(Pages.Navigation[strProp]);
    }
  },
  templateUrl: 'NavBarTemplate.html'
  };
});

模板:

<div id="NavBar" class="navigation">
    <ul>
        <li ng-repeat="oCurPage in aryPagesList">
            <a id="{{oCurPage.Name}}" ng-class="{active: oCurPage.Name==strActivePage}" href="{{oCurPage.BaseLink}}">{{oCurPage.Name}}</a>
        </li>
    </ul>
</div>

提前致谢!

4

1 回答 1

4

Html/Angularjs 不允许在属性名称中使用大写字符,因此将导航栏 html 更改为:

<nav-bar active-page="{{Pages.Navigation.Page2.Name}}"></nav-bar>

然后在您的指令范围内,您必须将 @ActivePage 更改为 @activePage

NavBarApp.directive('navBar', function(){
  return {
  restrict: 'E',
  replace: true,
  scope: {
    strActivePage: "@activePage"
  },
  controller: function($scope){
    $scope.aryPagesList = [];
    for(var strProp in Pages.Navigation){
      $scope.aryPagesList.push(Pages.Navigation[strProp]);
    }
  },
  templateUrl: 'NavBarTemplate.html'
  };
});

您的 plunkr 已修改:http ://plnkr.co/edit/6fMkmfxBd2I8nlfG8eLH

于 2013-05-01T19:40:22.100 回答