How to use angular js $ location.hash to change html element color on click?

I have three buttons labeled About Us, Contacts, and Services. Whenever I click the button, the hash value will be changed, and I used the concept of routing to go to different pages.

Now I want to use the function $location.hash()in AngularJS and change the color of the buttons whenever the hash value changes.

See the code I wrote below:

<div ng-controller="mainController">
    <a href = "#/aboutus" ng-class="{'active': location == '/aboutus'}">About us</a>
    <a href = "#/contactus" ng-class="{'active': location == '/contactus'}">Contact us</a>
    <a href = "#/services" ng-class="{'active': location == '/services'}">Services</a>
</div>

Here is the angular js code I wrote:

app.controller('mainController', ['$scope', '$location', function($scope,$location){
    var location = $location.hash();
}]);

Here's the css:

.active{
    background-color: red;
    color : white;
}
a{
    padding:10px;
    background-color: white;
    color: black;
    border: 1px solid black;
}

I don’t know what is wrong with the code, but I can’t get the color, the class is not added to the tag when clicked.

+4
source share
2 answers

, :

var location = $location.hash;

. view/template . , ,

$scope.location = $location.hash;

/, #. , hash;). #aboutus /aboutus

,

, . Angular . , , , . , .

angular.module('App', []);

angular
  .module('App')
  .controller('Foo', ['$scope', function($scope) {
    $scope.location = 'unset';
    $scope.setLocation = function(newLocation) {
      console.log(newLocation);
      $scope.location = newLocation;
    };
}]);
a.active {
  font-size: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App">
<div ng-controller="Foo">
  <a href="#firstLocation" ng-click="setLocation('first')" ng-class="{active: location == 'first'}">First Location</a>
  <a href="#somewhereElse" ng-click="setLocation('else')" ng-class="{active: location == 'else'}">Somewhere else</a>
  <p>{{ location }}</p>
</div>
</div>
Hide result

. . , , , . : AngularJS?

, , . , . , .

:


currentRoute →


currentRoute →
setRoute →


"setRoute"

+3

ng-

<a href = "#/aboutus" ng-class = "{'active': isActive('/aboutus')}">About us</a>
<a href = "#/contactus" ng-class = "{'active': isActive('/contactus')}">Contact us</a>
<a href = "#/services" ng-class = "{'active': isActive('/services')}">Services</a>

JS

$scope.isActive = function(url) {
    return $location.path().indexOf(url) > -1;
  }
0

Source: https://habr.com/ru/post/1670016/


All Articles