ng-toggle in AngularJS

Toggle as a basic feature in Front-end development, has been used for lots of modern websites. A lot of times, we need a toggle feature to show and hide a DOM element by clicking on another element, say a button. I believe there are plenty of ways doing it depends on the business requirement. In this article, I would like to share a few tricks that how I do toggle with both jQuery and AngularJS.


With jQuery Demo

HTML:

<body>
    <button>Custom</button>
    <span>From:
        <input type="text" id="from" />
    </span>
    <span>To:
        <input type="text" id="to" />
    </span>
</body>

CSS:

span {
    display: none;
}
.show {
    display: inline-block;
}

JS:

$("button").on("click", function () {
    var state = $(this).data('state');
    state = !state;
    if (state) {
        $("span").addClass("show");
    } else {
        $("span").removeClass("show");
    }
    $(this).data('state', state);
});

When coming to then AngularJS world, things become very different and interesting. Again, there are various ways to do it. Here is just my trick for ng-toggle in AngularJS:

With AngularJS Demo

HTML:

<body ng-app="ngToggle">
    <div ng-controller="AppCtrl">
        <button ng-click="toggleCustom()">Custom</button>
        <span ng-hide="custom">From:
            <input type="text" id="from" />
        </span>
        <span ng-hide="custom">To:
            <input type="text" id="to" />
        </span>
        <span ng-show="custom"></span>
    </div>
</body>

JS:

angular.module('ngToggle', [])
    .controller('AppCtrl',['$scope', function($scope){
        $scope.custom = true;
        $scope.toggleCustom = function() {
            $scope.custom = $scope.custom === false ? true: false;
        };
}]);

Update 1:

Thanks to the comments from :) and Iļja Ketris. They helped me improve the code to the shortest version: Demo


Update 2:

Thanks to the comments from Richard Bagnall and Zhao regarding to the jQuery toggleClass. I have put another demo here: Demo

Yang Zhao

Read more posts by this author.


Comment