2014-09-12 58 views
0

望着答案在這裏注入語法:https://stackoverflow.com/a/19272093/2547709

使用$注入語法我控制器結束這樣看:

class MyCtrl { 

    public static $inject: string[] = ['$scope']; 
    constructor($scope){ 
    // stuff 
    } 
} 
// register the controller 
app.controller("MyCtrl", MyCtrl); 

我的問題是 - 如果我發生了什麼想自己的自定義參數傳遞給構造以及任何注入的變量?:

class MyCtrl { 

    public static $inject: string[] = ['$scope']; 
    constructor($scope, customArg){ 
    // stuff 
    } 
} 
// Now how do I pass customArg in without it complaining? 
app.controller("MyCtrl", MyCtrl(customArg)); // Nope 

我覺得我失去了一些東西根本,用這種語法,你傳遞給.controller()函數的所有東西都必須使用angular註冊,所以我不應該試圖傳入自定義參數?或者我可以傳遞一個任意的值/對象?如果是的話如何?

+1

什麼是你想傳遞的東西的例子?你可以使用angular.value以角度註冊它嗎? – 2014-09-12 16:50:06

回答

3

customArg

如果會調用構造函數,則不能在自定義的參數傳遞。您可以可以然後註冊與Angular等其他東西服務,工廠,價值(常數)將傳遞給你的控制器。

更多:https://www.youtube.com/watch?v=Yis8m3BdnEM&hd=1

+1

感謝@basarat,我是您視頻的粉絲,他們真的幫助我掌握如何使用打字機慣用類似角度的東西! – ptr 2014-09-15 07:45:33

+0

非常感謝! – basarat 2014-09-15 08:52:20

+0

如果你有興趣,我有一個新的問題:[這裏](http://stackoverflow.com/questions/25844887/extending-angularjs-directives-with-typescript) – ptr 2014-09-15 09:33:18

0

對不起,我回答我沒有足夠的積分發表評論。

我有完全相同的情況,這裏是我的情況:

export abstract class DataService {

static $inject = ['$resource']; 
    private svc: ng.resource.IResourceClass<ng.resource.IResource<T>>; 

    constructor(
     protected $resource: ng.resource.IResourceService, url: string 

    ) { 
     this.svc = <ng.resource.IResourceClass<ng.resource.IResource<T>>>this.$resource(url, { id: '@id' }); 
    } 

    public get(id: number): ng.IPromise<T> { 
     return this.svc.get({ id: id }).$promise; 
    } 

} 

export class MyDataService 
    extends DataService<IItem> { 


    // big problem here!!! 
    constructor(
    ) { 
     super("/api/items/:id"); 
    } 

} 

看起來像我將不得不重複每個派生類的注入,並通過在超級...所以冗餘