Reputation: 12018
I created a list using divs and I want to change only background color of div when user select one from the list.
Currently I have done this by defining two different css classes with only difference is background color, and i set this style when user selects the div.
So is their anyway to change only background color without affecting existing style using angularJS?
Upvotes: 1
Views: 2048
Reputation: 6646
I hope this will help you , adding active class on clicked item
app.controller('MainCtrl', function($scope) {
$scope.items = [
'Page One',
'Page Two',
'Page Three'
];
$scope.selected = 0;
$scope.active = function(index) {
$scope.selected = index;
}
});
<li ng-repeat="item in items">
<a ng-class="{ active : $index == selected }" ng-click="active($index)">{{ item }}</a>
</li>
Upvotes: 1
Reputation: 5117
I have just started learning AngularJS, so this is kind of home work for me. I know this may not be the clean way or exactly what you want. See if it makes sense. If not let me know, I would love to improve.
Currently I have done this by defining two different css classes with only difference is background color
You can put background color into separate classes and toggle just that class keeping everything else same.
HTML
<div ng-app ng-controller="testCtrl" >
<div ng-repeat="item in items">
<div ng-class="item.class" ng-click="select(item)">{{item.text}}</div>
</div>
</div>
JS
function testCtrl($scope) {
$scope.items = [
{ text:'List item 1', class:'default normal' },
{ text:'List Item 2', class:'default normal' },
{ text:'List Item 3', class:'default normal' }
];
$scope.select = function(item) {
angular.forEach($scope.items, function (value, key) {
if(value == item) {
value.class = 'default select' // selected
}
else {
value.class = 'default normal' // restored
}
});
};
}
CSS
.default { font-size: 25px; padding: 10px; margin-bottom: 5px; }
.normal { background: yellow; }
.select { background: cyan; }
JSFiddle https://jsfiddle.net/po2o8f69/6/
Upvotes: 2