Cast angular scope variable to strong type

时间:2015-07-28 23:16:44

标签: angularjs typescript

I want to cast an angular scope variable to a type:

It might look something like this:

app.controller( 'PageLayoutController', function ( $scope )
{
    // Scope properties
    (PageMap)$scope.PageMap;

or

app.controller( 'PageLayoutController', function ( $scope )
{
    // Scope properties
    $scope.PageMap: PageMap;

Is it possible or must i declare a separate variable?:

var pageMap: PageMap;
$scope.PageMap = pageMap;

This is for typeahead sake.

2 个答案:

答案 0 :(得分:2)

Ideally you should define an interface and declare $scope with it:

interface IPageLayoutScope extends ng.IScope {
    PageMap: PageMap;
}

app.controller( 'PageLayoutController', function ( $scope: IPageLayoutScope)

That way $scope.PageMap will be defined already.

答案 1 :(得分:2)

You can do it this way, create a type deriving from IScope and add your properties to it. Example:

 interface PageLayoutVM extends ng.IScope{
     PageMap : PageMap;
 }

and use it

app.controller( 'PageLayoutController', function ( $scope:PageLayoutVM)

You will get ng.IScope only if you have angular.d.ts typings used in your application.

Also to add on, with the usage of TypeScript it is much easier to use it with controllerAs syntax and defining properties on the controller itself rather than using scope to set view model properties.

Something like:

 export interface PageLayoutVM {
     PageMap : PageMap;
     someChangehandler:(val:string)=>void;
 }

 class PageLayoutController implements PageLayoutVM {

    PageMap : PageMap; //public is implicit

    static $inject = ['$scope', 'myService']; //Just for demo if you are using scope specific methods like watch
    constructor(private $scope:ng.IScope,
                private myService:IMyService){

    }

    someChangehandler(val:string){ //Another public method
        this.myService.doSomething(val);
    }

    private doSomePrivateStuff(){
        //Do stuff...
    }

 }

With this when you write unit tests for your controller, you can write the test in TS itself with the type definitions it will be easy to lookup controller properties while writing tests.