Tuesday, February 5, 2013

Binding vs DOM manipulation. AngularJS vs jQuery

Bind JavaScript values (aka JSON) to HTML so incessant element placeholders won’t be needed as much

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

<body ng-app>


<label for="Multiplier">Multiplier</label><input ng-model="Multiplier" type="text"><br/>
<label for="Multiplicand">Multiplier</label><input ng-model="Multiplicand" type="text"><br/>
<input value="Multiply" type="button"/><br/>

<b>Product of {{Multiplier}} and {{Multiplicand}} is {{Multiplier * Multiplicand}}</b>




</body>
</html>


DOM Manipulation, very tedious:

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

<body>


<label for="Multiplier">Multiplier</label><input id="Multiplier" type="text"/><br/>
<label for="Multiplicand">Multiplier</label><input id="Multiplicand" type="text"/><br/>
<input value="Multiply" type="button" id="Multiply"/><br/>

<b>Product of <span id="MultiplierSpan"></span> and <span id="MultiplicandSpan"></span> is <span id="ProductSpan"></span></b>


<script type="text/javascript">

    $(function() {

        $('#Multiplier').keyup(function() {
            var multiplier = $('#Multiplier').val();
            $('#MultiplierSpan').text(multiplier);


            computeProduct();
        });

        $('#Multiplicand').keyup(function() {
            var multiplicand = $('#Multiplicand').val();
            $('#MultiplicandSpan').text(multiplicand);


            computeProduct();
        });


        function computeProduct() {
            var multiplier = $('#Multiplier').val();
            var multiplicand = $('#Multiplicand').val();

            var product = multiplier * multiplicand;
            $('#ProductSpan').text(product);
        }



    });

</script>

</body>
</html>

No comments:

Post a Comment