Reputation: 351
Here I'm trying to highlight the clicked area by adding active class using ui-sref-active
and $state.includes()
, but it's not working with $state.includes()
, but I'm getting the value true when I see its value through the controller. Help me out.
Here's the code snippet:
var app = angular.module('myApp', ['ui.router']);
app.controller('myCtrl', function($scope,$state) {
$scope.res=$state.includes('')
});
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('page');
$stateProvider
.state('page', {
url: '/page',
template: "u clicked on Luffy"
})
.state('paper', {
url: '/paper',
template: "u clicked on Zoro"
})
})
.active {
background-color: red;
color: white;
}
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<hr>
<h2>with ui-sref-active</h2>
<button ui-sref-active=active ui-sref='page'>Luffy</button>
<button ui-sref-active=active ui-sref='paper'>Zoro</button>
<hr>
<h2>with {'active':$state.includes('')}</h2>
<button ng-class="{'active':$state.includes('page')}" ui-sref='page'>Luffy</button>
<button ng-class="{'active':$state.includes('paper')}" ui-sref='paper'>Zoro</button>
<hr> Result=
<ui-view></ui-view>
<hr>
</div>
</body>
</html>
Upvotes: 1
Views: 501
Reputation: 7911
$state
won't be accessible in HTML, you can call a function in controller to achieve this
var app = angular.module('myApp', ['ui.router']);
app.controller('myCtrl', function($scope,$state) {
$scope.res = $state.includes('');
$scope.checkActive = function(state) {
return $state.includes(state)
}
});
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('page');
$stateProvider
.state('page', {
url: '/page',
template: "u clicked on Luffy"
})
.state('paper', {
url: '/paper',
template: "u clicked on Zoro"
})
})
.active {
background-color: red;
color: white;
}
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<hr>
<h2>with ui-sref-active</h2>
<button ui-sref-active=active ui-sref='page'>Luffy</button>
<button ui-sref-active=active ui-sref='paper'>Zoro</button>
<hr>
<h2>with {'active':$state.includes('')}</h2>
<button ng-class="{'active':checkActive('page')}" ui-sref='page'>Luffy</button>
<button ng-class="{'active':checkActive('paper')}" ui-sref='paper'>Zoro</button>
<hr> Result=
<ui-view></ui-view>
<hr>
</div>
</body>
</html>
Upvotes: 3