Make delicious recipes!

Angular.JS Controller


Angular.JS takes the concept of MVC (Model-View-Controller) to a next level by allowing you to bind
controllers (think functions) to views (think HTML DOM elements) such that the controller updates
the view when the model (think values) changes.

What???
Ok, as always an example will help to understand better.

Angular.JS Example

<HTML>
<HEAD>
    <title>Angular.JS Controller - PrismoSkills</title>
    <!-- Link Twitter Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <!-- Link Angular.JS -->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>

    <script>
        var moduleName = 'store';
        var moduleDependencies = [];
        var app = angular.module(moduleName, moduleDependencies);
        
        var model = {firstName: 'John', lastName: 'Rambo'};
        // Define a new controller with name 'MyController'
        // The controller updates the value whenever its changed in the model linked with ng-model below
        // Due to this, the model always remains updated.
        // Check this by typing in the text box below
        app.controller ('MyController', function MyFunction()
        {
            this.property1 = model;
            this.popname = function() {alert (this.property1.firstName);}
        });
    </script>
</HEAD>

<BODY> 
    <div ng-app="store">
        An angular expression: {{4+6}}
        <div ng-controller="MyController as foo" style="border:1px solid black; padding:20px; margin:11px; border-radius:11px; width:300px">
            Hello {{foo.property1.firstName}} {{foo.property1.lastName}}
            <BR><BR>
            <input type="text" ng-model="foo.property1.firstName"/>
            <BR><BR>
            <a href="" ng-click="foo.popname()">popup that name</a>
        </div>
    </div>
</BODY>
</HTML>


Result:

An angular expression: {{4+6}}
Hello {{foo.property1.firstName}} {{foo.property1.lastName}}



popup that name


Beauty of Angular.JS

Angular.JS shines in automatically updating the DOM view when the underlying model changes and vice versa.

When you type in the above box, the variable linked to it with ng-model="foo.property1.firstName" is
automatically updated and because of that, the DOM element corresponding to it is also automatically updated!!!







Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal