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.

No comments:

Post a Comment