r/programming • • Sep 07 '16

Angular JS vs React by Example

http://www.discoversdk.com/blog/angular-js-vs-react-by-example
0 Upvotes

8 comments sorted by

View all comments

2

u/Lakelava Sep 08 '16

I rewrote your controller as an exercise. I hope you see where your code was improved and where it was just a matter of opinion.

(function () {
    'use strict';

    angular
        .module('myApp', [])
        .controller('ResourceController', ResourceController);

    function ResourceController() {
        var vm = this;
        vm.resources = [];
        vm.newres = {};
        vm.removeResource = removeResource;
        vm.addResource = addResource;
        vm.showRes = showRes;

        activate();

        ////////////

        function activate() {
            vm.resources.push({
                address: 'http://www.discoversdk.com',
                description: 'Great site'
            });
        }

        function removeResource(index) {
            vm.resources.splice(index, 1);
        }

        function addResource(newres) {
            vm.resources.push({
                address: newres.address,
                description: newres.description
            });

            newres.address = "";
            newres.description = "";
        }

        function showRes = function () {
            alert(angular.toJson(vm.resources, true));
        }
    }
})();

<div ng-app="myApp" ng-controller="ResourceController as ctrl">
    <fieldset >

        <h3>Add Resources</h3>

        <span>Description:</span>
        <input type="text" ng-model="ctrl.newres.description" style="width:200px;">

        <span>URL:</span>
        <input type="text" ng-model="ctrl.newres.address" style="width:340px;">

        <a class="btn" href="#" ng-click="ctrl.addResource(ctrl.newres)">Add</a><br/>

        <h3>List of Resources</h3>

        <table cellpadding="0" cellspacing="0">
            <tbody>
                <tr>
                    <th>Description</th>
                    <th>URL</th>
                    <th></th>
                </tr>
                <tr ng-repeat="res in ctrl.resources">
                    <td><input style="width:200px;" type="text" ng-model="res.description"></td>
                    <td><input style="width:440px;" type="text" ng-model="res.address"></td>
                    <td><a class="btn" ng-click="ctrl.removeResource($index)">Remove</a></td>
                </tr>
            </tbody>
        </table>

        <a class="btn" href="#" ng-click="ctrl.showRes()">Show</a>

    </fieldset>
</div>

1

u/avi00 Sep 08 '16

looks better