Sunday, February 3, 2013

jQuery is too imperative, get declarative with AngularJS

Imperative approach is too ceremonial:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="jquery-1.9.0.min.js"></script>
</head>
<body>

Show Favorite Numbers: <input id="ShowFaveNumbers" type="checkbox">

<ul id="FaveNumbers">
    <li>5</li>
    <li>2</li>
    <li>0</li>
</ul>



<script>
    $(function() {

        function showOrHide() {
            var isChecked = $('#ShowFaveNumbers').is(':checked');

            var fn = $('#FaveNumbers');
            if (isChecked)
                fn.show();
            else
                fn.hide();
        }


        $('#ShowFaveNumbers').change(function() {
            showOrHide();
        });

        showOrHide();

    });
</script>


</body>
</html>


Get declarative with AngularJS:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="angular.min.js"></script>

</head>

<body ng-app>

Show Favorite Numbers: <input ng-model="ShowFaveNumbers" type="checkbox">

<ul ng-show="ShowFaveNumbers">
    <li>5</li>
    <li>2</li>
    <li>0</li>
</ul>



</body>
</html>


Live codes:

AngularJS: http://jsfiddle.net/t83UC/

jQuery: http://jsfiddle.net/ZzeuR/

No comments:

Post a Comment