Search code examples
angularjshrefngroute

angular - element to reflect which template is loaded to a view


I have a simple app using ngRoute: it has a view that loads different templates depending on the URL (#/1 => first template; #/2 => second template). I added 'a' elements to switch between these templates.

Is it possible to make the 'a' elements reflect the selected template? (e.g. to change their class depending on the current url).

<html ng-app="app">
    <a href='#/1'>one</a>
    <a href='#/2'>two</a>
    <div ng-view />
</html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular-route.min.js"></script>
<script>
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
    $routeProvider.when('/1', {template: 'first template'});
    $routeProvider.when('/2', {template: 'second template'});
    $routeProvider.otherwise({redirectTo: '/1'});
});
</script>

Solution

  • Take a look at the answer provided over at https://stackoverflow.com/a/18562339/665868 which in essence pretty much is what Vucko suggests.

    In my above linked SO question there are a bunch of different proposed solutions and you can really pick what suits you needs and level of complexity.