Change values ​​according to routeProvider parameter

 var mainApp = angular.module("mainApp", ['ngRoute']);

mainApp.controller('myCtrl', function($scope) {
    $scope.tab = 3;

});



mainApp.config(function($routeProvider) {
    $routeProvider
        .when('/cc', {
            templateUrl: 'cc.html',
        })
        .when('/pl', {
            templateUrl: 'pl.html',
        })

I use a route to display different pages depending on the user's choice. I use ng-classto change the appearance of the selected link to the page after the user clicks on this link. ng-classdepends on the value of the variable tabset in the controller.

Problem. When I reload the page www.foo.com/pl, the view shows pl.html, but the value tabis reset to 3. Thus, it makes the other link active, not "pl".

I want the value to tabchange depending on the page being loaded (even if I update the value, it should change accordingly). How can I achieve this? Any help would be appreciated.

+4
1

:

mainApp.config(function($routeProvider) {
$routeProvider
    .when('/cc', {
        templateUrl: 'cc.html',
        selected: 1 
    })
    .when('/pl', {
        templateUrl: 'pl.html',
        selected: 2
    })

$route :

mainApp.controller('myCtrl', function($scope, $route) {
    $scope.tab = $route.current.selected;
});

html ng-class:

<a href="/cc" ng-class="{active: tab == 1}">link1</li>
<a href="/pl" ng-class="{active: tab == 2}">link2</li>

- $location.

mainApp.controller('myCtrl', function($scope, $location) {
    $scope.tab = $location.path();
});

Html:

<a href="/cc" ng-class="{active: tab == '/cc/'}">link1</li>
<a href="/pl" ng-class="{active: tab == '/pl/'}">link2</li>
+3

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


All Articles