Monday, August 24, 2015

Ng-Controller in AngularJs

Ng-Controller in AngularJs

In this blog, I’m explaining about the ng-controller in angular js.

Example

First create an index.html file and add reference of anugular.min.js file like this:

<html >
<head>
    <title>Angular Js Controllers</title>
    <script src="/angular.min.js"></script>
    <script src="/app.js"></script>
</head>
<body>
</body>
</html>


Now create a javascript file named app.js and the reference of this file in index.html file just below the angular.min.js file in the head section of our html page.

Next in app.js :

var app = angular.module("myApp", []);


app.controller("myController", function () {
    this.firstname = "";
    this.lastname = "";

    this.showFullname = function (firstname, lastname) {
        alert(firstname + " " + lastname );
    }
});


First we create an angular module named “myApp”.

In this module, we create a controller named “myController”.

This controller will have two properties : firstname and lastname, and a method named showFullname().

Next in our index.html page add the angular module and controller like this:


<html ng-app="myApp">
<head>
    <title>Angular Js Controllers</title>
    <script src="/angular.min.js"></script>
    <script src="/app.js"></script>
</head>
<body ng-controller="myController as ctrl">
    <div>
        <p>
            Firstname :  <input type="text" ng-model="ctrl.firstname" />
        </p>
        <p>
            Lastname : <input type="text" ng-model="ctrl.lastname" />
        </p>
        <p>
            Fullname : {{ctrl.firstname + " " + ctrl.lastname}}
        </p>
        <p>
            <button type="button" ng-click="ctrl.showFullname(ctrl.firstname, ctrl.lastname)">Show</button>
        </p>
    </div>
</body>
</html>


We have added the ng-app in the <html> tag so that scope of the “myApp” angular module will be on whole html page.


Next in the <body>, we have added ng-controller directive with an alias name ctrl.


In the <input> tag s, we have used another angular directive ng-model , it is used to bind the controller’s properties to the HTML elements.


In the button, there is another angular directive ng-click, it is used to create click event in angular and this click event will call the controller’s method named showFullname(), this method will show fullname in the alert box.

Output             

Run the application :




Type the firstname and lastname in the repective textboxes:



As you can see, as you type the value in the textbox, you can see the it in fullname field this is because the firstname and lastname properties are evaluated in the angular expressions.


Next click on show button :











No comments:

Post a Comment