We can make a button behave like a toggling button by making a directive in AngularJS. It is very simple. You just need to bind the attribute and then check the condition.
First create a simple HTML :-
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/index.css">
<link rel="stylesheet" type="text/css" href="css/myApp.css">
<title>Hello World</title>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<div style="margin: 30px auto;margin-left: 55px;">
<input type="button" toggle value="button"></input>
<p>I am a {{toggleText}} button.</p>
<p>{{secondText}}</p>
</div>
</div>
<script src="js/angular.min.js"></script>
<script src="js/myApp.js"></script>
<script src="js/directive.js"></script>
</body>
</html>
In the above HTML, I have simply created a button and attached a directive to it named 'toggle'. The toggleText and secondText will get its value from the controller (through data binding).
Now make a controller:
var myApp = angular.module('myApp', []);
myApp.controller( "myController", function($scope) {
// alert("enter controller");
$scope.toggleText = 'toggling';
$scope.secondText = 'hello';
});
Now create a new file that contains the directive code :
myApp.directive('toggle', function () {
return {
restrict: 'A',
link: function ( $scope, elem, attrs) {
elem.bind("click", function () {
console.log('toggle start', elem)
if (elem.val() == "START") {
elem.val("STOP");
} else {
elem.val("START");
}
})
}
}
});
In this directive, as soon as you click on the button. It will get this element and bind the click function to it. If the text or value of the button is "START", it will change it to "STOP" and vice-versa. Hence, this button will behave as a toggle button that toggles the button text on each click.
0 Comment(s)