2017-02-18 102 views
1

我有三個按鈕,當用戶點擊基於散列值的按鈕時,應該更改按鈕的背景顏色,因爲我在此使用了路由概念。基於散列值單擊時更改按鈕的顏色

這裏是我寫 HTML

<body ng-controller="mainController"> 
    <ul class="list-group"> 
     <a ng-href="#/"><li class="list-group-item" ng-class="{'red': x=='#/'}" ng-click="showLocation()" >Home</li></a> 
     <a ng-href="#/Second-page"><li class="list-group-item" ng-class="{'red': x=='#/Second-page'}" ng-click="showLocation()" >Second page</li></a> 
     <a ng-href="#/Third-page"><li class="list-group-item" ng-class="{'red': x=='#/Third-page'}" ng-click="showLocation()" >Third page</li></a> 
    </ul> 
</body> 

CSS:

  .list-group-item.red{ 
      background-color: red; 
      color: white; 
      padding: 10px; 
     } 

JS:

var myApp = angular.module("myApp", ['ngRoute']); 
myApp.config(function($routeProvider){ 

$routeProvider 

.when("/", { 
    templateUrl: "main.html", 
    controller: "mainController" 
}) 
.when("/Second-page", { 
    templateUrl: "Second.html", 
    controller: "mainController" 
}) 
.when("/Second-page/:num", { 
    templateUrl: "Second.html", 
    controller: "mainController" 
}) 
.when("/Third-page", { 
    templateUrl: "Third.html", 
    controller: "secondController" 
}) 
.when("/Third-page/:num", { 
    templateUrl: "Third.html", 
    controller: "secondController" 
}) 

});

myApp.controller("mainController", ["$scope", "serviceName", "$routeParams", "$location", function($scope, serviceName, $routeParams){ 
$scope.x = window.location.hash; 
$scope.showLocation = function(){ 
    $scope.x = window.location.hash; 
} 

我的問題是location.hash工作不正常。點擊按鈕時,我會得到先前的哈希值。

例如,當我點擊第一個按鈕時什麼都沒有發生,當我點擊第二個按鈕時,第一個按鈕的哈希值被拍下,第一個按鈕被點擊。現在,當我點擊第三個按鈕時,第二個按鈕的散列值將被用作前一個散列值,第二個按鈕將變亮。

Css正在應用於以前的散列值。

任何人都可以爲我澄清這一點,我真的很困惑發生了什麼事情。 在此先感謝:)

+1

這可能是一個計時問題。嘗試用0長度'$ timeout'包裝你的'showLocation'登錄。 '$ timeout(function(){$ scope.x = window.location.hash;})' – haxxxton

+0

Got $ timeout沒有定義錯誤@haxxxton – Harish

+0

你需要注入'$ timeout'就像你爲'$ scope ' – haxxxton

回答

2

角有時作品「太快」了一些改變,被你的代碼的其餘部分「聽到」。

爲了解決這個問題,您可以將0長度$timeout添加到您的代碼中,以等待直到執行下一個摘要週期。

myApp.controller("mainController", ["$scope", "serviceName", "$routeParams", "$location", "$timeout", function($scope, serviceName, $routeParams, $location, $timeout){ 
    $scope.x = window.location.hash; 
    $scope.showLocation = function(){ 
     $timeout(function(){ 
      $scope.x = window.location.hash; 
     }); 
    } 
}]); 
-1

要改變按鈕的顏色,當它被點擊是通過編輯它的CSS文件。

.list-group-item.red{ 
 
      background-color: red; 
 
      padding: 10px; 
 
     } 
 
     
 
.list-group-item.red a{ 
 
      color: white; 
 
     } 
 

 
.list-group-item.red a:active{ 
 
      color: #fff; 
 
      /*you can add any value after color:*/ 
 
     }

+0

即使我知道這個過程,但我想通過使用角度js來改變顏色,而且也應該使用散列值來完成。我在這個問題上明確提到了我的要求。 – Harish