AngularJS:如何在按下时直接突出显示活动的导航项?

时间:2017-02-07 17:35:31

标签: javascript angularjs

我有一个由角度js制作的iPad应用程序。在导航菜单中添加了高亮功能。但我对它并不完全满意。用户体验并不是最好的。

按下菜单项时,不会立即突出显示。它不需要很长时间,但最好的方法是在按下项目时立即突出显示。我该怎么做才能做到这一点?

这是我的代码:

HTML:     

    <div class="ui-navbar">

        <ul>
            <li><a href="#!/" ng-class="getClass('/')" class="ui-state-persist ui-btn"><span>Home</span></a></li>
            <li><a href="#!/about" ng-class="getClass('/about')" class="ui-state-persist ui-btn"><span>About</span></a></li>
        </ul>

    </div><!-- /navbar -->

</div>

JS:

myApp.config(["$routeProvider", '$translateProvider', '$translatePartialLoaderProvider', function($routeProvider, $translateProvider, $translatePartialLoaderProvider)
{
    $routeProvider
    .when("/", {
        templateUrl : "home.html"
    })
    .when("/about", {
        templateUrl : "about.html"
    });

    $translateProvider.useLoaderCache(true);

    $translatePartialLoaderProvider.addPart('locale');
    $translatePartialLoaderProvider.addPart('header');
    $translatePartialLoaderProvider.addPart('footer');

    $translateProvider.useLoader('$translatePartialLoader', {
      urlTemplate: 'lang/{part}-{lang}.json'
    });
    $translateProvider.preferredLanguage('sv');

}]);

myApp.controller('HeaderCtrl', function ($scope, $translatePartialLoader, $location, $translate) {

  $translatePartialLoader.addPart('header');

  $scope.getClass = function (path)
  { 
      if ($location.path().substr(0, path.length) == path)
      { 
          if (path == "/" && $location.path() == "/")
          {
            return "ui-btn-active";
          } 
          else if (path == "/")
          {
            return "";
          } 

        return "ui-btn-active"
      } 
      else
      {
        return ""
      } 
  }

});

1 个答案:

答案 0 :(得分:0)

您可以在点击链接时设置CSS,而不是等待路由更改。考虑以下。

<body>
  <span ng-controller="NaviCtrl">
    <ul ng-repeat="item in navi.items">
      <li>
        <a ng-href="#{{ item.link }}"
           ng-class="{ active: item.active }"
           ng-bind="item.name"
           ng-click="navi.setActive(item)">
        </a>
      </li>
    </ul>
    <div ng-view></div>
  </span>
</body>
angular
.module('app', ['ngRoute'])
.value('navi', {
  items: [{
    name: 'Home',
    link: '/',
    active: true
  },{
    name: 'About',
    link: '/about',
    active: false  
  }],
  setActive: function(item) {
    angular.forEach(this.items, function(current) {
      current.active = angular.equals(current, item);
    });
  }
})
.config(function($routeProvider) {
    $routeProvider
    .when('/', {
        template : '<div>Home</div>'
    })
    .when('/about', {
        template : '<div>About</div>'
    });
})
.controller('NaviCtrl', function($scope, navi) {
  $scope.navi = navi;
});
ul > li .active {
  background-color: #00dd00;
}

imgur