Angular -ui-router: add css class if state match

simple wiki

I want to show the edit button on the navigation bar: status == 'page'

v0.2.10

.state('page',{
    url: "/wiki/{ns:[0-9a-zA-Z\-/_]+}/{wp:[0-9a-zA-Z\-/_]+}",
    templateUrl: "views/wiki/view.html",
    controller: "PageController"
})

I tried

<li ng-show="$state.$current.name == 'page'"><button type="button" class="btn btn-default navbar-btn">Edit</button></li>

and

<a ng-class="{hidden: $state.$current.name == 'page'}" class="btn navbar-btn btn-primary" ui-sref="edit">Edit</a>

even

$state.includes('page')

and

$state.is('page')
+4
source share
3 answers

I do this all the time in projects. The trick is to add a method to check the status.

$scope.is = function(name){
   return $state.is(name);
}

$scope.includes = function(name){
   return $state.includes(name);
}

Html:

<li ng-show="is('page')">
<a ng-class="{hidden: is('page')}">...</a>

I usually put them in the root area, but they are extremely useful. Another thing is to use directives ui-sref-active. They are very good when you create state links, and also want to automatically add a magic class when this state is active.

+11
source

, - ui-sref-active. :

<a ui-sref-active="active" ui-sref="login">Login</a>

, login, active a.

+5

Another way you can accomplish this is the way you wrote it.

app.run(function($rootScope, $state) {
    $rootScope.$state = $state;
});

This will make state available in all views so you can do something like

$state.current.name == 'page'
0
source

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


All Articles