Tuesday, July 15, 2014

Generating dynamic html using Angular.js

Carrying on from my last post angular can also be used to generate dynamic content as I learnt from one of the online tutorials I found.
To do that you need to use the following code:

<script type="text/javascript">
   
    function User(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;

        this.getFullName = function() {
            return this.firstName + " " + this.lastName;
        };
    }

    function UserController($scope) {
        $scope.userList = [
            new User("Misbah", "ul Haq"),
            new User("Mohammad", "Irfan"),
            new User("Saeed", "Ajmal")
        ];
    }
</script>

This code will create a class called User with properties firstName and lastName and a function called getFullName. I have then created an angular controller that contains a list of User.
In the html code below I will use a foreach loop (or angular’s take on c#’s foreach) and generate dynamic html to show the data extracted from angular’s controller.

<div ng-app>
    <div ng-controller="UserController">
        <p><b>Players</b></p>
        <div ng-repeat="user in userList">
            <a>{{user.getFullName()}}</a>
        </div>
    </div>
</div>

The code is pretty self-explanatory although if you do have questions you can refer to my last post which will help you understand angular’s keywords better.

Basic Angular.js application

To create an Angular.js application you first need to add the relevant reference as shown below:

<script src="http://code.angularjs.org/1.0.5/angular.js"></script>

Following this you can add a basic angular controller as shown below (note $scope is an angular keyword):

<script type="text/javascript">

    function ControllerName($scope) {
        $scope.Name = 'England';
    }

</script>

In the html section of this page you can use the following code to display data from the angular controller:

<div ng-app>
    <div ng-controller="ControllerName">
        <input type=text ng-model="Name" />
        <br />
        <p>{{Name}}</p>
    </div>
</div>


The keywords used in the example above are explained as follows:

ng-app: Defines the scope of angular’s application. Any angular specific code outside this div will not be handled by angular
ng-controller: Defines the scope of the controller ControllerName. Within this div we can work with variables defined within ControllerName as if they are local variables
ng-model: Defines which variable will the text box bind with
{{Name}}: Displays the value of variable Name


On this page if we enter anything new in the text box, it will automatically change the value of variable Name which will automatically update the value of {{Name}} shown below.