Sunday 5 June 2016

Create a sample application in Angular Js using Typescript

In this post we are going to see how to create a sample angular js application using Typescript, visual studio is a best editor for developing a Typescript applications, because it will compile and gives the intellisense  for the typings.


First we have to create a empty Asp.Net web project in visual studio, then we have to download the Typing file for angular to start the code. angular.d.ts, angular-route.d.ts , 




Now we will see a basic sample in which we have to create a module and a controller with one method. To start with Typescript we need the following files need to be added in our project. Don't consider the reference path , just find the file name from the list.

    <script type="text/javascript" src="scripts/angular.js"></script>
    <script type="text/javascript" src="scripts/angular-route.js"></script>
    <script type="text/javascript" src="scripts/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="scripts/bootstrap.js"></script>
    


Install the Typescript from the following link if not present in visual studio 
https://www.microsoft.com/en-us/download/details.aspx?id=48593

Once finish the download the above typing file , add that in your project.

/// <reference path="../scripts/typings/angularjs/angular.d.ts" />
/// <reference path="../scripts/typings/angularjs/angular-route.d.ts" />

Now create a typescript file app.ts and add the above reference in the first two line to get the intellisense while coding.

We have to do the things in order so first we have to create a model, then interface, then controllers, finally create module.
Get a Employee List is the sample we are currently trying 

Create a Model:
 In Typescript we can define the custom data types in model, then we can refer it in variable type, Now here Employee is the Type, so the sample will be like following.

app.ts
/// <reference path="../scripts/typings/angularjs/angular.d.ts" />
/// <reference path="../scripts/typings/angularjs/angular-route.d.ts" />

module DotnetVisio.Model {

    export class Employee {
        id: number;
        name: string;
        address: string;
    }
}


when you save the file it will generate the Js file, the output file will be.

Generated code in app.js
/// <reference path="../scripts/typings/angularjs/angular.d.ts" />
/// <reference path="../scripts/typings/angularjs/angular-route.d.ts" />
var DotnetVisio;
(function (DotnetVisio) {
    var Model;
    (function (Model) {
        var Employee = (function () {
            function Employee() {
            }
            return Employee;
        })();
        Model.Employee = Employee;
    })(Model = DotnetVisio.Model || (DotnetVisio.Model = {}));
})(DotnetVisio || (DotnetVisio = {}));


Create a Interfaces:
Now we have to create a Interface for Scope and that need to be derived from the ng.scope, because we have to specify or add the things which are need to be there in scope, then we have to specify that scope type in controller. Here in this sample we are going to add the IMainScope which is dervies from ng.IScope , then later we will specify that type in the controller , In sample we are specifying that scope must have the three property and a method.

IMainScope extends ng.IScope


app.ts
module DotnetVisio.Interfaces {
    export interface IMainScope extends ng.IScope {
        name: string;
        title: string;
        Employees: Array<Model.Employee>;
        getEmployees(): void;
    }
}


Create a Controller:
Creating a controller is little bit different from the normal angular js applications, Generally while creating controller we must pass the dependency as a parameters and map the attributes to the scope inside the controller like below.

Normal Angular JS Controller Code:
app.controller('MainController', ['$scope', function ($scope) {
        $scope.name = "Employees";
        $scope.title = "Angular Sample";

        $scope.getEmployees = function () {
            $scope.Employees = [
                { id: 1, name: "Rajesh", address: "Chennai" },
                { id: 2, name: "Suresh", address: "California" },
                { id: 3, name: "Ramu", address: "Pune" },
                { id: 4, name: "Shiny", address: "London" }
            ]
        }

    }]);

Now we will see how to create a equivalent Typescript code, in typescript we have to specify the dependency to inject using the $inject as Static array property or directly write as controller.$inject = [];

app.ts
module DotnetVisio.Controllers {

    export class MainController{
        private $scope: Interfaces.IMainScope;

        constructor($scope: Interfaces.IMainScope) {
            var ViewModel = this;
            ViewModel.$scope = $scope;
            ViewModel.$scope.title = "Angular Sample";
            ViewModel.$scope.name = "Employees";
            ViewModel.InitMethods();
        }

        private InitMethods(): void {
            var ViewModel = this;

            ViewModel.$scope.Employees = [];

            ViewModel.$scope.getEmployees = function () {

                ViewModel.$scope.Employees =  <Model.Employee[]>[
                    <Model.Employee>{ id: 1, name: "Rajesh", address: "Chennai" },
                    <Model.Employee>{ id: 2, name: "Suresh", address: "California" },
                    <Model.Employee>{ id: 3, name: "Ramu", address: "Pune" },
                    <Model.Employee>{ id: 4, name: "Shiny", address: "London" }
                ];

            }
            
        }
        
        static $inject = ['$scope'];
    }  
}

When you see above code we are injecting the $scope in $inject Array property to the controller, it is a static one, it can be declare in two ways one is declare as a static inside the controller or outside the controller function just add a property like MainController.$inject = ['$scope'], another thing here we have to notice is we are assign a this keyword to the variable named ViewModel, this is because the current constructor function instance refers to this, we must add the $scope property to the Controller function instance.so this.$scope is added from the injector , and also we are specifying the type of the scope as IMainScope, which have three properties and a method, after assign the $scope to the instance we have to access it through the instance variable, now there is a question we can use the this keyword instead of doing that why we have to create a another variable and assign the instance to that, because this parameter refers in root function cant be the same of child function. 

For example Here InitMethods() is a function which is used to map the methods in the scope $scope, when we use the this parameter inside the method is not the same as the this parameter used inside the method getEmployees, how means when you try to access the property Employees inside the getEmployees method like below this.$scope.Employees = [], it will show error as undefined, because both the this are refers to two different ones, now we are need the outer scope this, so to access the instance, we are maintain the instance in a variable named ViewModel, then access that inside the getEmployees() method will able to access everything in $scope like Employees Property.


Generated code in app.js
var DotnetVisio;
(function (DotnetVisio) {
    var Controllers;
    (function (Controllers) {
        var MainController = (function () {
            function MainController($scope) {
                var ViewModel = this;
                ViewModel.$scope = $scope;
                ViewModel.$scope.title = "Angular Sample";
                ViewModel.$scope.name = "Employees";
                ViewModel.InitMethods();
            }
            MainController.prototype.InitMethods = function () {
                var ViewModel = this;
                ViewModel.$scope.Employees = [];
                ViewModel.$scope.getEmployees = function () {
                    ViewModel.$scope.Employees = [
                        { id: 1, name: "Rajesh", address: "Chennai" },
                        { id: 2, name: "Suresh", address: "California" },
                        { id: 3, name: "Ramu", address: "Pune" },
                        { id: 4, name: "Shiny", address: "London" }
                    ];
                };
            };
            MainController.$inject = ['$scope'];
            return MainController;
        })();
        Controllers.MainController = MainController;
    })(Controllers = DotnetVisio.Controllers || (DotnetVisio.Controllers = {}));
})(DotnetVisio || (DotnetVisio = {}));


Create a Module:
Module must be created inside a module pattern like below and refers the controller with name and refers the function as second parameter

app.ts
module DotnetVisio.Module {

    var app = angular.module('app', []);
    app.controller('MainController', Controllers.MainController);    

}

Generated code in app.js
var DotnetVisio;
(function (DotnetVisio) {
    var Module;
    (function (Module) {
        var app = angular.module('app', []);
        app.controller('MainController', DotnetVisio.Controllers.MainController);
    })(Module = DotnetVisio.Module || (DotnetVisio.Module = {}));
})(DotnetVisio || (DotnetVisio = {}));


Html :
Now in html we have to refers all the JS files, including the app.js, because we are not referencing the app.ts file in HTML, because the Typescript  compiler converts the code in to java script, we have to refer that file 

In this sample i am using the Bootstrap also for a good looking UI. Here in this html there is no change  as usual we can declare the app module and controller . Variable can be accessed using the $scope map with the tag

<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
    <link rel="stylesheet" href="Content/bootstrap-theme.css" type="text/css" />
    <link rel="stylesheet" href="Content/bootstrap.css" type="text/css" />

    <script type="text/javascript" src="scripts/angular.js"></script>
    <script type="text/javascript" src="scripts/angular-route.js"></script>
    <script type="text/javascript" src="scripts/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="scripts/bootstrap.js"></script>
    <script type="text/javascript" src="app/app.js"></script>

</head>
<body ng-app="app">

    <div class="row" style="padding:20px"></div>
    <div class="row">
        <div class="col-lg-2"></div>
        <div ng-controller="MainController" class="panel panel-info col-lg-4">
            <div class="panel-heading">
                {{title}}
            </div>
            <div class="breadcrumb">{{name}}</div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-lg-8"></div>
                    <div class="col-lg-3">
                        <input value="Get Employees" type="button" 
                               class="btn btn-primary" 
                               ng-click="getEmployees()" />
                    </div>
                </div>
                <div class="row" style="margin-top:10px">
                    <ul class="list-group">
                        <li class="list-group-item list-group-item-info" 
                            ng-repeat="emp in Employees">
                            <div class="text-center text-muted row">
                                <span class="col-md-3">{{emp.id}}</span>  
                                <span class="col-md-5">{{emp.name}}</span>
                                <span class="col-md-4">{{emp.address}}</span>
                            </div>
                        </li>
                    </ul>
                </div>
                </div>
        </div>
    </div>
</body>
</html>

Full Source Code app.ts (Typescript)

/// <reference path="../scripts/typings/angularjs/angular.d.ts" />
/// <reference path="../scripts/typings/angularjs/angular-route.d.ts" />

module DotnetVisio.Model {
    export class Employee {
        id: number;
        name: string;
        address: string;
    }
}

module DotnetVisio.Interfaces {
    export interface IMainScope extends ng.IScope {
        name: string;
        title: string;
        Employees: Array<Model.Employee>;
        getEmployees(): void;
    }
}

module DotnetVisio.Controllers {

    export class MainController{
        private $scope: Interfaces.IMainScope;

        constructor($scope: Interfaces.IMainScope) {
            var ViewModel = this;
            ViewModel.$scope = $scope;
            ViewModel.$scope.title = "Angular Sample";
            ViewModel.$scope.name = "Employees";
            ViewModel.InitMethods();
        }

        private InitMethods(): void {
            var ViewModel = this;

            ViewModel.$scope.Employees = [];

            ViewModel.$scope.getEmployees = function () {

                ViewModel.$scope.Employees =  <Model.Employee[]>[
                    <Model.Employee>{ id: 1, name: "Rajesh", address: "Chennai" },
                    <Model.Employee>{ id: 2, name: "Suresh", address: "California" },
                    <Model.Employee>{ id: 3, name: "Ramu", address: "Pune" },
                    <Model.Employee>{ id: 4, name: "Shiny", address: "London" }
                ];

            }
            
        }
        
        static $inject = ['$scope'];
    }  
}

module DotnetVisio.Module {

    var app = angular.module('app', []);
    app.controller('MainController', Controllers.MainController);    

}



Full source code generated by Typescript as app.js
/// <reference path="../scripts/typings/angularjs/angular.d.ts" />
/// <reference path="../scripts/typings/angularjs/angular-route.d.ts" />
var DotnetVisio;
(function (DotnetVisio) {
    var Model;
    (function (Model) {
        var Employee = (function () {
            function Employee() {
            }
            return Employee;
        })();
        Model.Employee = Employee;
    })(Model = DotnetVisio.Model || (DotnetVisio.Model = {}));
})(DotnetVisio || (DotnetVisio = {}));
var DotnetVisio;
(function (DotnetVisio) {
    var Controllers;
    (function (Controllers) {
        var MainController = (function () {
            function MainController($scope) {
                var ViewModel = this;
                ViewModel.$scope = $scope;
                ViewModel.$scope.title = "Angular Sample";
                ViewModel.$scope.name = "Employees";
                ViewModel.InitMethods();
            }
            MainController.prototype.InitMethods = function () {
                var ViewModel = this;
                ViewModel.$scope.Employees = [];
                ViewModel.$scope.getEmployees = function () {
                    ViewModel.$scope.Employees = [
                        { id: 1, name: "Rajesh", address: "Chennai" },
                        { id: 2, name: "Suresh", address: "California" },
                        { id: 3, name: "Ramu", address: "Pune" },
                        { id: 4, name: "Shiny", address: "London" }
                    ];
                };
            };
            MainController.$inject = ['$scope'];
            return MainController;
        })();
        Controllers.MainController = MainController;
    })(Controllers = DotnetVisio.Controllers || (DotnetVisio.Controllers = {}));
})(DotnetVisio || (DotnetVisio = {}));
var DotnetVisio;
(function (DotnetVisio) {
    var Module;
    (function (Module) {
        var app = angular.module('app', []);
        app.controller('MainController', DotnetVisio.Controllers.MainController);
    })(Module = DotnetVisio.Module || (DotnetVisio.Module = {}));
})(DotnetVisio || (DotnetVisio = {}));



Output:






From this post you can see how to create a angular js applications using the Typescript. along with creation of module, controller in typescript 

59 comments:

  1. Nice Post! Thanks for sharing such an amazing article, really informative,it helps me a lot. For Latest Hindi News and Updates please visit: TV9 Bharatvarsh Media News

    ReplyDelete
  2. Nice information. Thanks for sharing such an amazing article. For Latest Telugu News and updates please visit our website: TV9 Telugu Media News

    ReplyDelete
  3. Thanks for the sharing information.

    Here you can get more online course details find here:
    https://www.qatraininginusa.com/



    ReplyDelete
  4. This is a very good article and nice collection of information , would love to read more of such blogs and also know our services

    Mobile application development in India
    Mobile application development in Delhi

    ReplyDelete
  5. Hello guys,
    I Read your blog and I found it is very good. There is a lot of good information on this blog, I'd like to Share and I think people will get a lot of support from this blog. Thanks for sharing this informative blog, please keep up and share some unique posts with us in the future.
    Digital Marketing Company in Jaipur
    Digital Marketing agency In Jaipur
    seo company In Jaipur

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. Nice article for getting good knowledge, hope people are liking it for their personal as well as professional welfare. Writing about a topic isn't easy, It took dedication and skills to write something good anout anything. In the meantime, do check out our website for enhancing your digital marketing skills and business productivity.
    digital marketing company in Jaipur
    PPC company in Jaipur
    social media marketing company in Jaipur
    content writers in Jaipur
    website development company in Jaipur

    ReplyDelete
  8. Keep sharing these articles. I find this article very helful, infact this blog provides latest information regarding different things. I always keep an eye on this blog for enhancing my knowledge. Keep doing good work. Hope people are sharing this article for their personal as well as professional use. In the meantime, do check out our website
    digital marketing company in Jaipur
    PPC company in Jaipur
    social media marketing company in Jaipur
    content writers in Jaipur
    website development company in Jaipur

    ReplyDelete
  9. Hii, i came across this blog while random browing and found great content. Such information adds up new things in the memory for staying updated in this society. If you also want to visit some good web pages then do check out our website https://digiroads.in for more offers and discounts on digital marketing services.
    digital marketing company in Jaipur
    PPC company in Jaipur
    seo company in Jaipur
    social media marketing company in Jaipur
    content writers in Jaipur
    website development company in Jaipur

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. such a nice post thanks for sharing this with us really so impressible and attractive post.
    Fashion bloggers in India

    ReplyDelete
  12. Hii,
    While browsing internet, I came across this beautiful article. This article is great for enhancing your knowledge regarding new things. I always support such bloggers who are investing their valuable time in assisting us with daily technologies and trends.
    digital marketing company in Jaipur
    Digital marketing company in Delhi
    Digital marketing company in Bangalore
    Digital marketing company in USA
    PPC company in Jaipur
    seo company in Jaipur
    social media marketing company in Jaipur
    content writers in Jaipur
    website development company in Jaipur
    mobile app development companies in Bangalore

    ReplyDelete
  13. Greeting for the day,
    Learning is a lifelong process and in order to learn new things, I always look out for new content and information. I found this blog while scrolling the web and glad to inform you that such piece of contents provides in depth knowledge regarding digital marketing. I also keep an eye on this blog in hope of acquiring new knowledge. Thankyou for your contribution to the society.
    digital marketing company in Jaipur
    Digital marketing company in Delhi
    Digital marketing company in Bangalore
    Digital marketing company in USA
    PPC company in Jaipur
    seo company in Jaipur
    social media marketing company in Jaipur
    content writers in Jaipur
    website development company in Jaipur
    mobile app development companies in Bangalore

    ReplyDelete
  14. Looking to enhance your digital marketing efforts?

    Well, we got you.

    We at Digiroads are available 24*7 for serving all your digital needs. We are the best digital marketing company in Jaipur in terms of customer satisfaction and services. Please visit our website https://digiroads.in for more information. You can also drop an email at info@digiroads.in for any queries.

    digital marketing company in Jaipur
    Digital marketing company in Delhi
    Digital marketing company in Bangalore
    Digital marketing company in USA
    PPC company in Jaipur
    seo company in Jaipur
    social media marketing company in Jaipur
    content writers in Jaipur
    website development company in Jaipur
    mobile app development companies in Bangalore

    ReplyDelete
  15. Hello, Excellent Blog with loads of information on this blog, Thanks for sharing with us. We ColourMoon Technologies specialists in making

    Mobile App Development Companies in Vizag
    Healthcare App Development in Vizag
    E Commerce App Development Company in Vizag
    Mobile app development companies in India
    Game Design Companies in Hyderabad
    Website Designers Agency in Kukatapally
    ERP Development Company in Visakapatnam
    Best Graphic Designers in Hyderabad

    https://thecolourmoon.com/

    ReplyDelete
  16. HI guys,
    This is a very good post, and I like it very much. For us, it's insightful and helpful. For a long time, I've been looking for this and I'm just really pleased to say that I'm working with this stuff as well. Thanks for sharing this with us.

    Digital Marketing Company in Jaipur
    Digital Marketing company In Delhi
    Digital Marketing Company in Bangalore
    SEO Company in Jaipur
    Website development Company in Jaipur
    PPC Company in Jaipur
    Digital Marketing Company in USA

    ReplyDelete
  17. Good blog,

    Digital Marketing Companies in Chennai, Website Design Companies in Chennai, SEO Companies in Chennai, Digital Marketing Company Chennai, Web Design Company Chennai

    https://wisewebtek.com

    ReplyDelete
  18. Everyone wants to learn and earn from digital marketing. So, here are some links for digital marketing enthusiast and business owners to get latest digital marketingn tips and tricks. Boomark these or visit on daily basis.

    digital marketing blogs

    digital marketing blogs

    digital marketing blogs

    digital marketing blogs

    digital marketing blogs

    Digital marketing blogs

    Digital marketing blogs

    Digital marketing blogs

    Digital marketing blogs

    Digital marketing blogs

    Digital marketing blogs

    Digital marketing blogs

    ReplyDelete
  19. HI guys,
    This is a very good post, and I like it very much. For us, it's insightful and helpful. For a long time, I've been looking for this and I'm just really pleased to say that I'm working with this stuff as well. Thanks for sharing this with us.

    Digital Marketing Company in Jaipur
    Digital Marketing company In Delhi
    Digital Marketing Company in Bangalore
    SEO Company in Jaipur
    Website development Company in Jaipur
    PPC Company in Jaipur
    Digital Marketing Company in USA

    ReplyDelete
  20. Top ranking is very important for your online business and it is the only way to success online. According to the sources, the first page of Google gives 95 percent web traffic whereas if your website are coming to the second page, then you will get only 5 percent of the total traffic, so rank your website at first page on google is important for your business.

    SEO Company in Bangalore

    ReplyDelete
  21. Hey There. I found your blog using msn. This is a very well written article.
    I'll make sure to bookmark it and come back to read more of your useful info. Thanks for the post. I'll definitely return.
    Thank you!!
    Here My website for Best seedbox

    ReplyDelete
  22. Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place.
    visit here
    visit here
    visit here
    visit here
    visit here

    ReplyDelete
  23. Incredible post I might want to thank you for the endeavors you have made in composing this fascinating and learned article
    click here
    click here
    click here
    click here
    click here

    ReplyDelete
  24. Thank you for such a wonderful contribution for sharing this valuable and understanding article with us Best SEO Company Vadodara then plusply digital is offering the best SEO Services in ahmedabad for your business website or Online Marketing.

    ReplyDelete
  25. Their main objective is to ensure that once the dedicated development team is through with the product, it fulfills all expectations. The owner has to analyze current trends and drive the creative efforts in the right direction.

    ReplyDelete
  26. Firstly, your DevOps consultancy will need figure out the size and functionality of your existing database, and how it interacts with applications. Ideally, the cloud DevOps consulting services you employ should identify the number of CPU cores on the existing server and its memory size, along with the number of instances in scope and the estimated number of databases per instance.

    ReplyDelete
  27. Hey!! This is such an amazing article that I have read today & you don't believe that I have enjoyed a lot while reading this amazing article. thanx for sharing such an amazing article with us.best seedbox

    ReplyDelete
  28. The Article designs are very nice and this is a very unique content than any other designing blogs in my point of view. Keep updating more in future.
    Here My website for seedbox

    ReplyDelete
  29. Hey There. I found your blog using msn. This is a very well written article.
    I'll make sure to bookmark it and come back to read more of your useful info. Thanks for the post. I'll definitely return.
    Thank you!! venture jolt

    ReplyDelete
  30. Wow that's really good and informative post, I just read it. Thanks for this quality content. For more information please click on it Dedicated Development Team .

    ReplyDelete
  31. Wow I really enjoyed to read that all i will always follow You thanks for the great article.
    It conatains so good knowledge. Full of informative article.
    Here My website for Best seedbox

    ReplyDelete
  32. There are many ways to define an open source ticketing system. The easiest way to describe it is: The open-source ticketing system is a solution that any company can use. It is available to everyone, including your business. Companies benefit in many ways. First of all, it allows customers to report problems online.
    Please visit: open source helpdesk system
    osticket

    ReplyDelete
  33. We all know that laptop has very importance in our daily life because our mostly works are based on the laptop. At any age you are, you still need a good and best performance base laptop for your daily work and extra activities you want to do. If you asked me that which laptop complements the demand of every basic task then I recommend you to check Toshiba Satellite c55-c5390 review

    ReplyDelete
  34. Hey, I enjoyed this blog, where you talk about the growth of freelancers' income, just like full-time full stack developer salary. One of the great freelancing platforms for java developers is Eiliana.com. Take a look at the freelancing platform too. It is a new yet great platform for technical experts.

    ReplyDelete
  35. Fascinating, this is such a valuable tutorial for us since we are to engage a digital transformation consultant.

    ReplyDelete
  36. Such a amazing blog it really helps me and have some good knowledge

    ReplyDelete