2014-09-12 57 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"); 
    } 

} 

看起来像我将不得不重复每个派生类的注入,并通过在超级...所以冗余