Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Changing button text (toggle text) on click in AngularJS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 9.97k
    Comment on it

    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 :-

            <link rel="stylesheet" type="text/css" href="css/index.css">
            <link rel="stylesheet" type="text/css" href="css/myApp.css">
            <title>Hello World</title>
        <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>
            <script src="js/angular.min.js"></script>
            <script src="js/myApp.js"></script>
            <script src="js/directive.js"></script>

    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") {
                    } else {

    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)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: