Make delicious recipes!

Angular.JS Controller




Angular.JS Example

The below code shows an example for ng-show and ng-hide directives.
These are very simple to understand directives which show or hide an element based on the expression value.
<HTML>
<HEAD>
    <title>Angular.JS Controller - PrismoSkills</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
    <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);
        
        app.controller ('MyController', function MyFunction()
        {
            this.property1 = {flag: true, counter: 5};
        });
    </script>
</HEAD>

<BODY> 
    <div ng-app="store">
        <div ng-controller="MyController as foo"
                style="border:1px solid black; padding:20px; margin:11px; border-radius:11px; width:300px">
            <div ng-hide="foo.property1.flag">Div 1: Hide if flag is true</div>
            <div ng-show="foo.property1.flag">Div 2: Show if flag is true</div>
            <div ng-show="foo.property1.counter==5">Div 3: Show if counter is 5</div>
            <BR><BR>
            foo.property1.flag value: <input type="text" ng-model="foo.property1.flag"/>
            <BR><BR>
            foo.property1.counter value: <input type="text" ng-model="foo.property1.counter"/>
        </div>
    </div>
</BODY>
</HTML>


Result:

Div 1: Hide if flag is true
Div 2: Show if flag is true
Div 3: Show if counter is 5


foo.property1.flag value:

foo.property1.counter value:


Explanation of ng-show directive

The ng-show directive shows or hides a component based on the expression.
The ng-hide directive is just the opposite convenience for ng-show.


Is it worth the effort?

This might look trivial to do without Angular.JS but imagine this flexibility for several DOM elements automatically updating based on the Model.
Next chapters would explain more on how Angular.JS removes the repetitive mundane work out of the way by adding more directives like this.

Arguably, it is worth learning Angular.JS only if a medium to high degree of such complexity is expected between the DOM and the View.
For quasi-static pages, it may be more easier to go with regular HTML and JavaScript.







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