Angular typescript controller as

Angular Controllers with TypeScript

We’ve moved much of our code over to TypeScript. There are a lot of benefits. To start, you can just dump your javascript files directly into typescript “.ts” files and it will compile them for you and web-essentials plugins will minify them for you everytime you click “save”.

The next step is to take advantage of the programming language and start using it as a real tool. The most effective approach to dealing with AngularJs in TypeScript, for me, has been to simply turn every controller and factory into a class object.

Here is an example of a simple controller that is attached to a pre-existing application “app” and pulls data using a factory called adminfact.

/// /// interface IRouteParams extends ng.route.IRouteParamsService < userId: number; >class UserCtrl < public valueToUseOnPage:string; static $inject = [ '$http', '$log', '$location', '$window', 'adminFact', '$cookies','$routeParams']; constructor( private $http: ng.IHttpService, private $log: ng.ILogService, private $location: ng.ILocationService, private $window: ng.IWindowService, private adminFact: Application.Services.IMyService, private $cookies: ng.cookies.ICookiesService, private $routeParams: IRouteParams ) < var userId: number = $routeParams.userId; console.log($routeParams.userId); this.valueToUseOnPage = "DAN " + userId; adminFact.GetOffices(function (data: Object, status:number) < >); > > app.controller("UserCtrl", UserCtrl);

All that does is let typescrypt know where to get the object types and create some intelliesense for us. Usually you can just drag the file right over and drop it on your typescript page, but sometimes I’ve found I have to type it in manually.

Then we have route parameters. We use ng-route for our SPAs, so we constantly need to get the route parameters. Here’s how you get them in TypeScript.
First, you’re going to create an “interface”. That’s really just kind of a template that helps TypeScript know that you’ve got a RoutParms object and it’s got a few features. Almost like a model in MVC.

interface IRouteParams extends ng.route.IRouteParamsService

now you need to get that into your controller’s class. It’s pretty simple once you figure it out.

The class has a “constructor”. That’s just where everything from the outside is going to be defined. In our case, we’re bringing in a bunch of stuff. It’s just like how you do in the controller line for normal angular, but it’s “injected”. The first step is to do the $inject, like this:

static $inject = [ '$http', '$log', '$location', '$window', 'adminFact', '$cookies','$routeParams'];

Now, that’s actually optional. However, without it, your minification doesn’t work. It’s exactly like how you used to do this:

app.controller("somename",["$http", "$scope",function($http,$scope)< -some stuff here >]);
app.controller("somename", function($http,$scope)< -some stuff here >);

but they both work if not minified.

Anyway, the next step is to actually build that constructor:

constructor( private $http: ng.IHttpService, private $log: ng.ILogService, private $location: ng.ILocationService, private $window: ng.IWindowService, private adminFact: Application.Services.IMyService, private $cookies: ng.cookies.ICookiesService, private $routeParams: IRouteParams )

there are a lot of these ng.Interfaces. You can download just about anything you want from here https://github.com/DefinitelyTyped/DefinitelyTyped

Читайте также:  METANIT.COM

Just pop those files in any directory and Typescript will find them and just figure it out. (very very nice).

Now, here’s the next step. If you want to get something to your webpage, it has to be declared as a public variable in the class. As you can see, we have

public valueToUseOnPage:string;

then, inside our constructor, we can assign that a value. Here’s the uber simple look.

if we had a controller like this:

class UserCtrl < public valueToUseOnPage:string; constructor( ) < this.valueToUseOnPage = "DAN "; >> app.controller("UserCtrl", UserCtrl);

and our route setup was like this

then on our HTML view we could have:

That’s about as uber simple as it gets.

Let’s now move on to Factories, which is where the rubber hits the road.

About MacGyver

I’ve worked with database systems for over 20 years, and started my own company in 2000. Almost all my business consists of internal database systems, either ERP or CRM. All of my programming is Microsoft C# or VB.net using Transact SQL.

About This Site

Morris Development has been specializing in internal database system design and integration since 1999. We provide long-term management and support of secure data systems for many businesses as well as developing the more complex code structures for ERP systems like Intellievent, Apidas, and AVMS.

This site is primarily for our developers to keep track up various technologies and updates that are used by Morris Development.

Источник

Kode Yak

Thoughts on JavaScript, AngularJS, NodeJS, TypeScript and SharePoint development

AngularJS via TypeScript – Controllers

This is the 1st in a series of articles about developing for AngularJS using TypeScript. The articles in the series are:

Introduction

As I mentioned in my previous post I am currently using AngularJS a lot at the moment and am trying to write the majority of my JavaScript code using TypeScript. To be able to do this effectively I wanted to put together a set of base classes in TypeScript that I could use in my AngularJS projects.

A lot of simple AngularJS demos on the web seem to start by just creating a controller so I’m going to do the same here. Let’s take a simple example of an AngularJS controller written in JavaScript:

function MyController( $scope ) < $scope.message = < title: "Hello World!!" >; >

This could then be saved in a file called controller.js and then used in a web page like the following:

<!DOCTYPE html> <html> <head> <title>AngularJS in TypeScript</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script> <script type="text/javascript" src="controller.js"></script> </head> <body> <div ng-app="" ng-controller="MyController"> <h1>></h1> </div> </body> </html>

Which would then output something like the following:

Hello World!!

As you can see it’s a very simple and trivial AngularJS example and one that shouldn’t be difficult to write using TypeScript. The first thing we have to do is delete our controller.js file and create a new file, called controller.ts. We can then populate controller.ts with the following code:

When compiled this would produce our controller.js with the following JavaScript:

var MyController = (function () < function MyController($scope) < $scope.message = < title: "Hello World!!" >; > return MyController; >)();

and if you refresh the page you see the same Hello World!! text. Wow! I bet you’re amazed with that eh? Nope?

Читайте также:  Streams and files java io
Adding Types

All we’ve done is prove we can write some TypeScript which creates a simple controller but doesn’t really show why we’d want to use TypeScript in the first place. One of the useful features when writing TypeScript is the code-completion help that you get but to get proper benefit from that you have to be explicit with types. In the example above we passed a $scope property to the constructor but didn’t specify a type so would get no help with the methods and properties available to us.

If we now change the code in controller.ts to be as follows:

interface IMyMessage < title: string; >interface IMyScope extends ng.IScope < message: IMyMessage; >class MyController < constructor( $scope: IMyScope ) < $scope.message = < title: "Hello World!!" >; > >

You can see above that our $scope parameter in the constructor has an explicit type, IMyScope and that is defined to inherit from ng.IScope (this is an interface representing the properties and methods available on an AngularJS $scope). The IMyScope type has a message property which itself is of type IMyMessage, where IMyMessage has a string property called title. If you now recompile controller.ts it will produce exactly the same JavaScript in controller.js as it did before.

That’s because all we added were type definitions which are not relevant to the JavaScript output but are useful for us when editing the code. So we’re writing extra code just so we can get some better code-completion then? So far, yes, but if we extend it a bit further we will begin to see other benefits.

Triggering Events

If we now change our web page and add a button below the h1 element:

. <div ng-app="" ng-controller="MyController"> <h1>></h1> <button ng-click="clickMe()">Do It!</button> </div> .

The standard thing to do next would be to change the controller so that it adds a method called clickMe to the scope, like the following:

. class MyController < constructor( $scope: IMyScope ) < $scope.message = < title: "Hello World!!" >; $scope.clickMe = function() < alert( "Hello" ); >; > >

Then clicking on the button will show an alert dialog with the Hello text in it.

Personally I’m not a fan of these inline functions at the best of times but even more so when writing in TypeScript. Instead I’d like to write a proper method and have that called by the click event. Since the $scope is provided to my controller through the AngularJS dependency injection pattern it’s not a trivial matter to add a clickMe method to it. It is, however, easy to add a new method to my controller and I could store a reference to my controller on the scope so that the view/html can get access to the method.

To do this I could change my controller to look like the following:

. class MyController < constructor( $scope: IMyScope ) < $scope.events = this; $scope.message = < title: "Hello World!!" >; > clickMe() < alert( "Hello" ); >>

Then the button in my html code could be updated to the following:

. <button ng-click="events.clickMe()">Do It!</button> .
Referencing $scope

Now, what if I wanted to display the message.title property from the $scope in my alert box when the button is clicked? To do this I’d need to store a reference to my $scope so that the clickMe method get to it. This can be done as follows:

. class MyController < scope: IMyScope; constructor( $scope: IMyScope ) < this.scope = $scope; $scope.events = this; $scope.message = < title: "Hello World!!" >; > clickMe() < alert( this.scope.message.title ); >>
Code Reuse and Inheritance

For me the first 2 lines of the constructor seem like common things that I’d like to have on all my controllers but I don’t really want to have to add them every time. This is where TypeScript really comes into it’s own for me – inheritance. I can now write a base controller class like the following:

module KodeYak < export interface IScope extends ng.IScope < events: Controller; >export class Controller < scope: IScope; constructor( $scope: IScope ) < this.scope = $scope; this.scope.events = this; >> >

and I can change the MyController class to the following:

module MyTestApp < export interface IMyMessage < title: string; >export interface IMyScope extends KodeYak.IScope < message: IMyMessage; >export class MyController extends KodeYak.Controller < scope: IMyScope; constructor( $scope: IMyScope ) < super( $scope ); $scope.message = < title: "Hello World!!" >; > clickMe() < alert( this.scope.message.title ); >> >

I added use of TypeScript modules to the code above so as to namespace the code to prevent similar class names from interfering with each other. (This means that the ng-controller tag in the html file should be changed to MyTestApp.MyController)

Читайте также:  Php zip command line
Conclusion

Hopefully in this post I’ve started to show the merits of using TypeScript to write AngularJS applications and in future posts I intend to expand on this with the intention of putting together a library of TypeScript classes that can be used to make AngularJS application even easier to develop!

Источник

Урок 5. AngularJS. Controller as синтаксис

Уроки AngularJS

От автора: в этом уроке мы познакомимся с новым синтаксисом для работы с контроллерами — это так называемый controller as синтаксис. Использование данного варианта позволяет исключить использование сервиса $scope в работе, а также позволяет сделать сложный код чуть более понятным. Также в уроке мы научимся создавать методы контроллера.

lesson

Все уроки курса:

Warning: include(seolink.php): failed to open stream: No such file or directory in /home/webformy/public_html/wp-content/plugins/wfm-premium/templates/single-premium.php on line 78

Warning: include(): Failed opening ‘seolink.php’ for inclusion (include_path=’.:/opt/alt/php74/usr/share/pear’) in /home/webformy/public_html/wp-content/plugins/wfm-premium/templates/single-premium.php on line 78

Комментарии (3)

Продолжительность курса: 10:16:32

Автор: Андрей Кудлай

Меня зовут Андрей Кудлай — один из авторов проекта webformyself и практикующий веб-разработчик. Имею хорошие навыки работы с HTML, CSS, jQuery, PHP, MySQL, Bootstrap, CakePHP, Yii2, WordPress, OpenCart. Являюсь автором нескольких курсов-бестселлеров издательства WebForMySelf.com

Описание курса: Приветствую Вас, друзья, в новом цикле уроков, посвященных знакомству с JS фреймворком AngularJS и изучению основ работы с ним. Собственно, данный цикл будет называться просто — Уроки AngularJS (на русском языке). Для чего нужен данный фреймворк и какова сфера его применения?

Все права защищены © 2023
ИП Бернацкий Анрей Васильевич
Служба поддержки

Источник

Оцените статью