toggle and set button as active button using Angularjs - javascript

I have set of four button and I want to make them toggle and active on click of the button. Currently my buttons are get toggled on double click.
The solution what I am expecting is, when I click on the button current btn should get highlighted and data should be displayed and when I click on the next button, previous content should get hidden and current content should be visible.
Code:
(function() {
var app = angular.module('myapp', []);
app.controller('toggle', function($scope) {
$scope.Ishide_bank = true;
$scope.bank = function() {
$scope.Ishide_bank = $scope.Ishide_bank ? false : true;
};
$scope.Ishide_asset = true;
$scope.assets = function() {
$scope.Ishide_asset = $scope.Ishide_asset ? false : true;
};
$scope.Ishide_address = true;
$scope.address = function() {
$scope.Ishide_address = $scope.Ishide_address ? false : true;
};
$scope.Ishide_personal = true;
$scope.personal = function() {
$scope.Ishide_personal = $scope.Ishide_personal ? false : true;
};
});
})();
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body ng-controller="toggle">
<div>
<button class="bttn" ng-click="address()">Address</button>
<button class="bttn" ng-click="personal()">Personal-details</button>
<button class="bttn" ng-click="bank()">Bank-Account</button>
<button class="bttn" ng-click="assets()">Asset</button>
</div>
<div ng-hide="Ishide_address">
<h1>Btn 1</h1>
</div>
<div ng-hide="Ishide_bank">
<h1>Btn 2</h1>
</div>
<div ng-hide="Ishide_asset">
<h1>Btn 3</h1>
</div>
<div ng-hide="Ishide_personal">
<h1>Btn 4</h1>
</div>
</body>
</html>
Plunker : https://plnkr.co/edit/8hr9zXXkgBkBZRqUjpks?p=preview
Please let me know where I am going wrong.

first of your script order is wrong!
angular lib should be first then custom script.js
also below is the simplest way to do what you trying to do.
(function() {
var app = angular.module('myapp', []);
app.controller('toggle', function($scope) {
$scope.view = 'default';
$scope.toggle_view = function(view) {
$scope.view = $scope.view === view ? 'default' : view;
};
});
})();
.bttn {
background: #eee;
border: 1px solid #aaa;
}
.bttn.active {
background: yellow;
}
.bttn:focus {
outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
<div ng-controller="toggle">
<div>
<button class="bttn" ng-class="{'active': view === 'address'}" ng-click="toggle_view('address')">Address</button>
<button class="bttn" ng-class="{'active': view === 'personal'}" ng-click="toggle_view('personal')">Personal-details</button>
<button class="bttn" ng-class="{'active': view === 'bank'}" ng-click="toggle_view('bank')">Bank-Account</button>
<button class="bttn" ng-class="{'active': view === 'asset'}" ng-click="toggle_view('asset')">Asset</button>
</div>
<div ng-show="view === 'address'">
<h1>Address View</h1>
</div>
<div ng-show="view === 'bank'">
<h1>Bank View</h1>
</div>
<div ng-show="view === 'asset'">
<h1>Asset View</h1>
</div>
<div ng-show="view === 'personal'">
<h1>Personal View</h1>
</div>
</div>
</div>

Related

Angular js toggle event is not working correctly

My toggle works fine but when I click the button again it will not reset all. The tab which is open will stay open or close (if it's close). It is behaving like it doesn't want to reset to its original form. Can someone suggest me what I am doing wrong, please
<md-card>
<md-card-content>
<button ng-click="Custom()">Cick Here</button>
<div>
<div ng-repeat="search in vm.searchResults">
<md-card ng-click="callaction=!callaction">
<md-card-content>
<br />
<div ng-repeat="sponsor in search.scp">
<div ng-repeat="cin in sponsor.ci">
<div ng-repeat="po in cin.po" >
<p></p>
<span> {{sponsor.Name }}</span>
<span ng-repeat="prod in po.prods">
<img ng-src="{{img/cc2.ico}}">
</span>
<md-list>
<md-list-item ng-hide="callaction">
<div class="outside">
<div ng-repeat="delivery in po.deliveryAddresses" class='extra divInner'>
{{delivery.PracticeName}} <br /> <span ng-show="delivery.LineTwo">{{ delivery.LineTwo}}
</div>
</div>
</md-list-item>
</md-list>
</div>
</div>
</div>
</md-card-content>
</md-card>
</div>
</div>
</md-card-content>
</md-card>
Javascript
$scope.callaction = true;
$scope.Custom = function () {
$scope.callaction = !$scope.callaction;
};
As you can see running the code snippet,
angular works fine...
function TestCtrl($scope, cards) {
var vm = $scope;
vm.cards = cards;
vm.collapseCard = function(card) {
card.callaction = false;
};
vm.expandCard = function(card) {
card.callaction = true;
};
vm.Custom = function(event, card) {
card.callaction
? vm.collapseCard(card)
: vm.expandCard(card)
;
};
vm.collapseAll = function(event) {
vm.cards.forEach(vm.collapseCard);
};
vm.expandAll = function(event) {
vm.cards.forEach(vm.expandCard);
};
vm.toggleAll = function(event) {
vm.cards.forEach(function(card) {
vm.Custom(event, card);
});
};
vm.checkboxStyleBehaviour = function(event) {
var someCollapsed = vm.cards.some(
function(card) { return card.callaction === false; }
);
if(/* there are */ someCollapsed /* cards left */) {
return vm.expandAll();
}
return vm.collapseAll();
};
}
angular
.module('test', [])
.controller('TestCtrl', TestCtrl)
.constant('cards', Array.from({length: 20},
(_, i) => ({id: ++i, callaction: true})
))
;
.toggle-disabled {
visibility: hidden;
}
button {
margin-right: 5px;
}
.cbox {
background: lightcoral;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
<div ng-controller="TestCtrl">
<button ng-click="expandAll($event)">Expand All Cards</button>
<button ng-click="collapseAll($event)">Collapse All Cards</button>
<button ng-click="toggleAll($event)">Toggle All Cards</button>
<button ng-click="checkboxStyleBehaviour($event)" class="cbox">Checkbox Style?</button>
<hr />
<hr />
<div ng-repeat="card in cards track by $index">
<button ng-click="Custom($event, card)">Toggle</button> <strong ng-class="{false: 'toggle-disabled'}[card.callaction]">
{{card.id}} - I Am Active
</strong>
<hr />
</div>
</div>
</section>

how to use $scope inside .on click event?

I'm very new to Angular js and am testing a few functions with a simple data-parser project (Plunkr). Right now, I'm having trouble accessing $scope variable within a jQuery on click event. I would like to keep some elements hidden until an image is clicked. While I can set ng-hide to true within the controller, $scope does not appear to work inside an on click handler. Please help.
zodiac.html
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div id="container" ng-app="myApp" ng-controller="myCtrl">
<div>
<h1>What Animal Are You?</h1>
<div id="selectPicture"></div>
</div>
<div id="zodiac" ng-hide="disappear">
<h1>Your Zodiac</h1>
<div id="your-zodiac">
</div>
<br>
<h1>Avoid these Animals</h1>
<div id="hateDiv">
</div>
<br>
<h1>These Are Your Besties</h1>
<div id="loveDiv">
</div>
</div>
<script src="scripts.js"></script>
</div>
</body>
scripts.js
function d(c) {
console.log(c)
}
var app = angular.module('myApp', [])
app.controller('myCtrl', function($scope, $http) {
$http.get('zodiac.json').success(function(data) {
$scope.disappear = true //WORKS HERE
$scope.animalsData = data
angular.forEach($scope.animalsData, function(item) {
$('#selectPicture').prepend('<img src="' + item.picture + '" alt="' + item.animal + '">')
})
$('#selectPicture').on('click', 'img', function($scope) {
$scope.disappear = false //DOES NOT WORK HERE
$('#zodiac div').empty();
findZodiac(this.alt, "#your-zodiac", true);
})
function findZodiac(animal, e, test) {
angular.forEach($scope.animalsData, function(item) {
if (item.animal == animal) { //look for the right object 'item', when found, get the image
//item.picture
$(e).prepend('<img src="' + item.picture + '">')
if (test == true) {
loveHate(item.hate, "#hateDiv")
loveHate(item.love, "#loveDiv")
}
return
}
})
}
function loveHate(array, e) {
angular.forEach(array, function(value) { //loops through an array, get each animal
findZodiac(value, e, false)
})
}
});
})
In my opinion you should not do DOM manipulation directly when using AngularJS. Use the directives provided by AngularJS instead. Here are the template and controller code if you do so -
zodiac.html
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div id="container" ng-app="myApp" ng-controller="myCtrl">
<div>
<h1>What Animal Are You?</h1>
<div id="selectPicture">
<img ng-repeat="animal in animalsData"
ng-src="{{animal.picture}}"
alt="{{animal.animal}}"
ng-click="disappear=false; findZodiac(animal)" />
</div>
</div>
<div id="zodiac" ng-hide="disappear">
<h1>Your Zodiac</h1>
<div id="your-zodiac">
<img ng-src="{{selectedAnimal.picture}}" alt="{{selectedAnimal.animal}}" />
</div>
<br>
<h1>Avoid these Animals</h1>
<div id="hateDiv">
<img ng-repeat="animal in selectedAnimal.hate"
ng-src="{{animal.picture}}"
alt="{{animal.animal}}" />
</div>
<br>
<h1>These Are Your Besties</h1>
<div id="loveDiv">
<img ng-repeat="animal in selectedAnimal.love"
ng-src="{{animal.picture}}"
alt="{{animal.animal}}" />
</div>
</div>
<script src="scripts.js"></script>
</div>
</body>
scripts.js
var app = angular.module('myApp', [])
app.controller('myCtrl', function($scope, $http) {
$scope.animalsData = [];
$scope.selectedAnimal = {};
$scope.disappear = true;
$scope.findZodiac = function(animal) {
$scope.selectedAnimal = animal;
};
$http.get('zodiac.json').success(function(data) {
$scope.animalsData = data;
});
});
In AngularJS $scope is a global variable for your controller, You don't need to pass it like this. directly use it as
$('#selectPicture').on('click','img',function(){
$scope.disappear=false;//this will work
$('#zodiac div').empty();
findZodiac(this.alt,"#your-zodiac",true);
})
check this corrected version
scope object only available in angular world.

Set CSS property with js click event handler

I am trying to create an onclick event which will show/hide elements of an array however I am struggling with the showSubTabGroup() function below.
Sidenote: Eventually I would like to make this onmouseenter and onmouseleave, rather than 'click' as you see below.
I would like to be able to click on a div and show subsequent div's below as you might expect from a navigation feature.
The console is not returning any errors, however the 'click' function seems alert("CLICKED") properly.
Any help would be greatly appreciated.
Problem:
Tab.prototype.showSubTabGroup = function (tabIndex, subTabIndex) {
this.tab[tabIndex].addEventListener('click', function () {
alert("CLICKED");//Testing 'click' call
for (var i = subTabIndex; i < this.subTabGroup; i++) {
this.subTab[i].style.display = "";
}
});
}
function Tab (subTabGroup) {
this.tab = document.getElementsByClassName("tab");
this.subTab = document.getElementsByClassName("sub-tab");
this.subTabGroup = subTabGroup;
}
Tab.prototype.hideSubTabs = function () {
for (var i = 0; i < this.subTab.length; i++) {
this.subTab[i].style.display = "none";
}
}
Tab.prototype.showSubTabGroup = function (tabIndex, subTabIndex) {
this.tab[tabIndex].addEventListener('click', function () {
for (var i = subTabIndex; i < this.subTabGroup; i++) {
this.subTab[i].style.display = "";
}
});
}
var tab = new Tab(3);
tab.hideSubTabs();
tab.showSubTabGroup(0,0);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Responsive Nav</title>
</head>
<body>
<!-- JQuery CDN -->
<script src="http://code.jquery.com/jquery-3.1.0.js"></script>
<div class="container">
<div class="tab">
<p>TAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
</div>
<div class="container">
<div class="tab">
<p>TAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
</div>
<div class="container">
<div class="tab">
<p>TAB</p>
</div>
<div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
<div class="sub-tab">
<p>SUBTAB</p>
</div>
</div>
</div>
<script type="text/javascript" src="tab.js"></script>
<script type="text/javascript" src="tabEvents.js"></script>
</body>
</html>
The problem of what is this inside the click. It is not your tab code, it is the reference to the element that you clicked on. You need to change that by using bind
Tab.prototype.showSubTabGroup = function (tabIndex, subTabIndex) {
this.tab[tabIndex].addEventListener('click', (function () {
for (var i = subTabIndex; i < this.subTabGroup; i++) {
this.subTab[i].style.display = "";
}
}).bind(this));
}
As I read your post, I assume hideSubTabs() is working properly. In that case I will suggest to use in showSubTabGroup():
this.subTab[i].style.display = "initial";
instead of
this.subTab[i].style.display = "";
"initial" will set to its default e.g. as "block" for div and "inline" for span
I see that you also have included jQuery. If I may ask why don't jQuery functions which will do the same with less code:
$('.tab').on('click',function() {
$(this).closest('.container').find('.sub-tab').toggle()
})
$('.tab').click();
$('.tab')[0].click();

Looking for a Dual Listbox with AngularJS and Bootstrap

I am looking for a component like this to be included in my project:
http://geodan.github.io/duallistbox/sample-100.html
I want to install it with npm.
The problem is that I tested some of the examples which are over there, but without success (I get exceptions, or there is no npm, only bower)
These are the examples I tested.
https://github.com/alexklibisz/angular-dual-multiselect-directive
https://github.com/frapontillo/angular-bootstrap-duallistbox
http://www.bootply.com/mRcBel7RWm
Any recommendations about one with AngularJs, Bootstrap, and npm?
This might solve your requirement: Dual list Box
app.js
angular.module('plunker', [])
.controller('MainCtrl', function($scope, utils) {
$scope.list1 = [],
$scope.list2 = [];
utils.insertData($scope.list1, 5);
})
.factory('utils', function Utils() {
return {
insertData: function(list, numItems) {
for (var i = 0; i < numItems; i++) {
list.push({
id: i + 1,
title: 'item' + (i + 1)
});
}
},
getIndexesFromList: function(list) {
var newList = [];
for (var i in list) {
if (typeof list[i].id === "number" && newList.indexOf(list[i].id) === -1) newList.push(list[i].id)
}
return newList;
},
getAllSelectedItems: function(list) {
var newList = [];
newList = list.filter(function(el) {
return el.active === true;
});
return newList;
},
addListIfNoExists: function(list2, newListToAppend) {
var indexes = this.getIndexesFromList(list2);
var newList = [];
for (var i in newListToAppend) {
if (indexes.indexOf(newListToAppend[i].id) === -1) list2.push(newListToAppend[i])
}
return list2;
}
}
})
.directive('dualList', function(utils) {
function _controller($scope) {
$scope.selectAllItem = function(list, checked) {
list.map(function(item) {
item.active = checked
return item;
});
};
$scope.getAllSelectedItems = function(list) {
return utils.getAllSelectedItems(list);
}
$scope.moveItemToRightList = function() {
var newListToAppend = $scope.list1.filter(function(el) {
if (el.active === true) {
el.active = false;
return el;
}
});
if (newListToAppend.length > 0) {
$scope.list1 = $scope.list1.filter(function(el) {
return utils.getIndexesFromList(newListToAppend).indexOf(el.id) === -1;
});
$scope.list2 = utils.addListIfNoExists($scope.list2, newListToAppend);
if ($scope.list1.length === 0) $scope.checked1 = false;
}
};
$scope.moveItemToLeftList = function() {
var newListToAppend = $scope.list2.filter(function(el) {
if (el.active === true) {
el.active = false;
return el;
}
});
if (newListToAppend.length > 0) {
$scope.list2 = $scope.list2.filter(function(el) {
return utils.getIndexesFromList(newListToAppend).indexOf(parseInt(el.id)) === -1;
});
$scope.list1 = utils.addListIfNoExists($scope.list1, newListToAppend);
if ($scope.list2.length === 0) $scope.checked2 = false;
}
};
}
return {
restrict: "E",
scope: true,
controller: _controller,
templateUrl: "dualList.html"
};
});
dualList.html
<div class="container">
<br />
<div class="row">
<div class="dual-list list-left col-md-5">
<div class="well text-right">
<div class="row">
<div class="col-md-3">
<div class="checkbox">
<label>
<input type="checkbox"
ng-model="checked1"
ng-click="selectAllItem(list1, checked1)">
Todo {{getAllSelectedItems(list1).length}}/{{list1.length}}
</label>
</div>
</div>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-search"></span>
<input type="text"
name="SearchDualList"
ng-model="search1"
class="form-control"
placeholder="search" />
</div>
</div>
</div>
<ul class="list-group">
<a class="list-group-item"
href=""
data-id="{{item.id}}"
ng-click="item.active = !item.active"
ng-class="{active: item.active}"
ng-repeat="item in list1|filter: search1">{{item.title}}</a>
</ul>
<p ng-if="(list1 | filter:search1).length == 0">Sin Datos</p>
</div>
</div>
<div class="list-arrows col-md-1 text-center">
<button ng-click="moveItemToLeftList()"
class="btn btn-default btn-sm move-left">
<span class="glyphicon glyphicon-chevron-left"></span>
</button>
<button ng-click="moveItemToRightList()"
class="btn btn-default btn-sm move-right">
<span class="glyphicon glyphicon-chevron-right"></span>
</button>
</div>
<div class="dual-list list-right col-md-5">
<div class="well">
<div class="row">
<div class="col-md-3">
<div class="checkbox">
<label>
<input type="checkbox"
ng-model="checked2"
ng-click="selectAllItem(list2, checked2)">
Todo {{getAllSelectedItems(list2).length}}/{{list2.length}}
</label>
</div>
</div>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-search"></span>
<input type="text"
name="SearchDualList"
ng-model="search2"
class="form-control"
placeholder="search" />
</div>
</div>
</div>
<ul class="list-group">
<a class="list-group-item"
href=""
data-id="{{item.id}}"
ng-click="item.active = !item.active"
ng-class="{active: item.active}"
ng-repeat="item in list2|filter: search2">{{item.title}}</a>
</ul>
<p ng-if="(list2 | filter:search2).length == 0">Sin Datos</p>
</div>
</div>
</div>
</div>
index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script data-require="jquery#*" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://code.angularjs.org/1.3.0/angular.js"></script>
<link data-require="bootstrap#*" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link data-require="bootstrap#*" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" />
<link data-require="font-awesome#*" data-semver="4.3.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" />
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<dual-list data-list1="list1" data-list2="list2"></dual-list>
</body>
</html>
style.css
.dual-list .list-group {
margin-top: 8px;
}
.list-arrows {
padding-top: 100px;
}
.list-arrows button {
margin-bottom: 20px;
}
.list-group-item.active, .list-group-item.active:hover, .list-group-item.active:focus {
border-color: white;
}
.input-group-addon {
top: 0;
}
I think this link will help you.
Try this npm for angular 2/4 just you need to install with npm
https://www.npmjs.com/package/ng2-dual-list-box

adding and removing classes in angularJs using ng-click

I am trying to work how to add a class with ngClick. I have uploaded up my code onto plunker Click here. Looking at the angular documentation i can't figure out the exact way it should be done. Below is a snippet of my code. Can someone guide me in the right direction
<div ng-show="isVisible" ng-class="{'selected': $index==selectedIndex}" class="block"></div>
Controller
var app = angular.module("MyApp", []);
app.controller("subNavController", function ($scope){
$scope.toggle = function (){
$scope.isVisible = ! $scope.isVisible;
};
$scope.isVisible = false;
});
I want to add or remove "active" class in my code dynamically on ng-click, here what I have done.
<ul ng-init="selectedTab = 'users'">
<li ng-class="{'active':selectedTab === 'users'}" ng-click="selectedTab = 'users'"><a href="#users" >Users</a></li>
<li ng-class="{'active':selectedTab === 'items'}" ng-click="selectedTab = 'items'"><a href="#items" >Items</a></li>
</ul>
You just need to bind a variable into the directive "ng-class" and change it from the controller. Here is an example of how to do this:
var app = angular.module("ap",[]);
app.controller("con",function($scope){
$scope.class = "red";
$scope.changeClass = function(){
if ($scope.class === "red")
$scope.class = "blue";
else
$scope.class = "red";
};
});
.red{
color:red;
}
.blue{
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ap" ng-controller="con">
<div ng-class="class">{{class}}</div>
<button ng-click="changeClass()">Change Class</button>
</body>
Here is the example working on jsFiddle
There is a simple and clean way of doing this with only directives.
<div ng-class="{'class-name': clicked}" ng-click="clicked = !clicked"></div>
you can also do that in a directive, if you want to remove the previous class and add a new class
.directive('toggleClass', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function() {
if(element.attr("class") == "glyphicon glyphicon-pencil") {
element.removeClass("glyphicon glyphicon-pencil");
element.addClass(attrs.toggleClass);
} else {
element.removeClass("glyphicon glyphicon-ok");
element.addClass("glyphicon glyphicon-pencil");
}
});
}
};
});
and in your template:
<i class="glyphicon glyphicon-pencil" toggle-class="glyphicon glyphicon-ok"></i>
You have it exactly right, all you have to do is set selectedIndex in your ng-click.
ng-click="selectedIndex = 1"
Here is how I implemented a set of buttons that change the ng-view, and highlights the button of the currently selected view.
<div id="sidebar" ng-init="partial = 'main'">
<div class="routeBtn" ng-class="{selected:partial=='main'}" ng-click="router('main')"><span>Main</span></div>
<div class="routeBtn" ng-class="{selected:partial=='view1'}" ng-click="router('view1')"><span>Resume</span></div>
<div class="routeBtn" ng-class="{selected:partial=='view2'}" ng-click="router('view2')"><span>Code</span></div>
<div class="routeBtn" ng-class="{selected:partial=='view3'}" ng-click="router('view3')"><span>Game</span></div>
</div>
and this in my controller.
$scope.router = function(endpoint) {
$location.path("/" + ($scope.partial = endpoint));
};
var app = angular.module("MyApp", []);
app.controller("subNavController", function ($scope){
$scope.toggle = function (){
$scope.isVisible = ! $scope.isVisible;
};
$scope.isVisible = false;
});
<div ng-show="isVisible" ng-class="{'active':isVisible}" class="block"></div>
I used Zack Argyle's suggestion above to get this, which I find very elegant:
CSS:
.active {
background-position: 0 -46px !important;
}
HTML:
<button ng-click="satisfaction = 'VeryHappy'" ng-class="{active:satisfaction == 'VeryHappy'}">
<img src="images/VeryHappy.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'Happy'" ng-class="{active:satisfaction == 'Happy'}">
<img src="images/Happy.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'Indifferent'" ng-class="{active:satisfaction == 'Indifferent'}">
<img src="images/Indifferent.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'Unhappy'" ng-class="{active:satisfaction == 'Unhappy'}">
<img src="images/Unhappy.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'VeryUnhappy'" ng-class="{active:satisfaction == 'VeryUnhappy'}">
<img src="images/VeryUnhappy.png" style="height:24px;" />
</button>
If you prefer separation of concerns such that logic for adding and removing classes happens on the controller, you can do this
controller
(function() {
angular.module('MyApp', []).controller('MyController', MyController);
function MyController() {
var vm = this;
vm.tab = 0;
vm.setTab = function(val) {
vm.tab = val;
};
vm.toggleClass = function(val) {
return val === vm.tab;
};
}
})();
HTML
<div ng-app="MyApp">
<ul class="" ng-controller="MyController as myCtrl">
<li ng-click="myCtrl.setTab(0)" ng-class="{'highlighted':myCtrl.toggleClass(0)}">One</li>
<li ng-click="myCtrl.setTab(1)" ng-class="{'highlighted':myCtrl.toggleClass(1)}">Two</li>
<li ng-click="myCtrl.setTab(2)" ng-class="{'highlighted':myCtrl.toggleClass(2)}">Three</li>
<li ng-click="myCtrl.setTab(3)" ng-class="{'highlighted':myCtrl.toggleClass(3)}">Four</li>
</ul>
CSS
.highlighted {
background-color: green;
color: white;
}
I can't believe how complex everyone is making this. This is actually very simple. Just paste this into your html (no directive./controller changes required - "bg-info" is a bootstrap class):
<div class="form-group col-md-12">
<div ng-class="{'bg-info': (!transport_type)}" ng-click="transport_type=false">CARS</div>
<div ng-class="{'bg-info': transport_type=='TRAINS'}" ng-click="transport_type='TRAINS'">TRAINS</div>
<div ng-class="{'bg-info': transport_type=='PLANES'}" ng-click="transport_type='PLANES'">PLANES</div>
</div>
for Reactive forms -
HTML file
<div class="col-sm-2">
<button type="button" [class]= "btn_class" id="b1" (click)="changeMe()">{{ btn_label }}</button>
</div>
TS file
changeMe() {
switch (this.btn_label) {
case 'Yes ': this.btn_label = 'Custom' ;
this.btn_class = 'btn btn-danger btn-lg btn-block';
break;
case 'Custom': this.btn_label = ' No ' ;
this.btn_class = 'btn btn-success btn-lg btn-block';
break;
case ' No ': this.btn_label = 'Yes ';
this.btn_class = 'btn btn-primary btn-lg btn-block';
break;
}

Categories