Reputation: 136
How to apply ng-style on ng-click dynamically without using ng-class in angular? something like changing color for selected active menu only. something like this DEMO but with ng-style. Below is my code which is toggle function. Can anyone solve this by changing the code or use your own example to change color or font-size for active item when clicked and rest of the items to default state.
<div ng-style="x.selected && {'color':'white','font-weight':'bold'}"
ng-click="select(x)" ng-repeat="x in myData" ></div>
var app = angular.module('anApp', ['angular.filter']);
app.controller('aCtrl', function($scope) {
$scope.data = [
{
"id": 100,
"value": "2452"
},
{
"id": 100,
"value": "2458"
},
{
"id": 1,
"value": "2457"
},
{
"id": 1,
"value": "2459"
},
{
"id": 4,
"value": "2460"
},
{
"id": 5,
"value": "3458"
}
];
$scope.select = function(x){
x.selected = !x.selected;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
<div ng-app="anApp" ng-controller="aCtrl">
<div ng-style="x.selected && {'color':'red','font-weight':'bold'}"
ng-click="select(x)" ng-repeat="x in data" >
{{x.value}}
</div>
</div>
Upvotes: 1
Views: 1307
Reputation: 1094
Can you try using $index as below example with plunker below,
http://plnkr.co/edit/Z977olOlajTNZENbqx7D?p=preview
<div ng-repeat="x in data" ng-click="setSelected($index)" ng-style="$index === selectedId && {'background' :'red' }">
{{x.value}}
</div>
Upvotes: 1
Reputation: 17289
Try like this.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.menuItems = ['Home', 'Contact', 'About', 'Other'];
$scope.activeMenu = $scope.menuItems[0];
$scope.setActive = function(menuItem) {
$scope.activeMenu = menuItem
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
<div ng-app="plunker" ng-controller="MainCtrl">
<div class="account-item" ng-repeat='item in menuItems'>
<div class="account-heading" ng-style="activeMenu === item && {'background' :'red' }">
<h4 class="account-title">
<a href="#/Messages" ng-click="setActive(item)"> {{ item }}</a>
</h4>
</div>
</div>
</div>
Upvotes: 1