2015-10-16 26 views
0

我試圖僅在我處於根路徑時才添加類。根據angularjs中的位置添加和刪除類

我有什麼想

我希望我的頭有一個類fixed當它在根路徑和它去別處時被刪除。

我所做的

我在我的html:

<header ng-class="currentPath === '/' ? 'main-header fixed' : 'main-header' "> 

和我的控制器上:

'use strict'; 

angular.module('hipodromoApp') 
    .controller('MainCtrl', function ($scope, $route, $location, $rootScope) { 
    $scope.awesomeThings = [ 
     'HTML5 Boilerplate', 
     'AngularJS', 
     'Karma' 
    ]; 

    $scope.currentPath = $location.path(); 


    }); 

我的HTML總是返回虛假的main-header沒有fixed類。

問題

我怎麼一個名爲fixed類添加到我的html,只有當我在根路徑/並刪除它時,我去別的地方?

謝謝!

回答

0

我能夠解決這個問題。

我創建了以下內容的index_controller

'use strict'; 

/** 
* @ngdoc function 
* @name hipodromoApp.controller:IndexControllerCtrl 
* @description 
* # IndexControllerCtrl 
* Controller of the hipodromoApp 
*/ 
angular.module('hipodromoApp') 
    .controller('IndexControllerCtrl', function ($scope, $location, $rootScope) { 
    $scope.awesomeThings = [ 
     'HTML5 Boilerplate', 
     'AngularJS', 
     'Karma' 
    ]; 

    // console.log($location.path()); 


    }); 

// this will run every time the route changes 
angular.module('hipodromoApp') 
    .run(['$rootScope','$location', function($rootScope, $location) { 
    $rootScope.$on('$routeChangeSuccess', function() { 
     var location = $location.path(); 

     if (location == '/') { 
       $rootScope.bodyClass = 'fixed'; 
     }else{ 
      $rootScope.bodyClass = ''; 
     } 
    }); 
    }]); 

,並在index.html的添加了控制器

<div class="" ng-view="" ng-controller="IndexControllerCtrl"></div> 

,只是添加了這個

<header class="main-header {{bodyClass}}"> 

{{bodyClass}}將改變到fixed當它進入根路徑和t當它位於不同的路線中時,母雞爲空字符串。

我不確定這是解決這個問題的最佳方法,但是做了我需要的工作。

0

你做什麼對我有用。對於我來說,從ng-class中移除主標題並將其放在普通的課程中是有道理的,但這可能是個人的好處。

您是否console.log您的$ scope.currentPath?我認爲它可能不是/。 你確定你正在尋找合適的範圍嗎?沒有ng-重複子範圍或沿着這些線的東西。