Tuesday, October 20, 2015

The very first AngularJS application

I am very late to AngularJS development, and learning from various articles and videos. One of the Youtube video helps to start from very basics. To just check whether your page is using Angularjs  include the script path and test with an Angularjs expression.

Here is an example:

<html ng-app >
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="../js/angular.js"></script>

    <script>
        var name = "Angular";
    </script>
</head>

<body>
    <h1> Hello Angular! </h1>
    10/2 is:  {{10/2}}
</body>
</html>

If you include the correct angularjs script file, you will get the result as 5 other wise you will just see expression as it is like {{10/2}}.

Now we will move to our first Angularjs application. We have to define/use, a ng-app, angular application, a ng-controller, angular controller, and a model. First define these in the script file.

This defines the application for this page
var app = angular.module('app', []);

This creates the controller called MainController, inside the controller i am creating a model, message, and assign to the global scope.

app.controller('MainController', obj2);

function obj($scope)
{
    $scope.message = "Hello, Angular!!!";
}

Now in html page we have to tell which one is application, and which portion of the page is going to managed by the controller. I have declared my html as follows:

<html ng-app="app" >
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="../js/angular.js"></script>
    <script src="script.js"></script>
</head>
<body ng-controller="MainController">
    <h1> {{message}} </h1>
    <h3>{{message.length}} </h3>
</body>
</html>

I am setting the ng-app to the root html and whole body is managed / controlled by the controller. If you want to learn AngularJS, this article: AngularJS Tutorial: A Comprehensive 10,000 Word Guide  by Todd Motto is great one.