打字稿+角度

时间:2013-08-14 08:24:43

标签: javascript angularjs typescript angularjs-scope

我正在使用带有Angular的Typescript,如http://www.youtube.com/watch?v=WdtVn_8K17E

所述
class MyController {
    thescope: any;
    static $inject = ['$scope'];

    constructor($scope) {
        $scope.vm = this;
        this.thescope = $scope;
    }

    ...
}

我想创建一个这个控制器的实例。我必须使用什么作为$ scope参数?

var mc = new MyController(whatParameterHere?); // 

5 个答案:

答案 0 :(得分:1)

如果您正在寻找在控制器和/或指令之间调用的常用方法,请使用服务。

如果您想操纵dom,请使用指令。

回答你的问题:

module myApp.ctrl {
    myApp.controller("MyController", function($scope) {
        return new MyController($scope);
    }

    class MyController {
        thescope: any;
        static $inject = ['$scope'];

        constructor($scope) {
            $scope.vm = this;
            this.thescope = $scope;
        }

        ...
    }
}

答案 1 :(得分:1)

你应该使用服务而不是控制器,

服务你可以注入它并在你的应用程序中调用它的功能。

例如,如果要从api中调用数据:

module Data {
    export interface IDataService {
        http:ng.IHttpService;
        fetch:()=>ng.IPromise<string>;
    }
    export class DataService implements IDataService{
        http:ng.IHttpService;

        static $inject = ["$http"];
        constructor($http:ng.IHttpService) {
            this.http = $http;
        }

        fetch():ng.IPromise<string> {
            return this.http.get("link");
        }
    }
}
angular.module("app").service("DataService", Data.DataService);

如果你想使用像jstree这样的插件,你应该为它创建一个指令并在其中注入DataService并使用你想要的函数。

答案 2 :(得分:0)

在AngularJS中你的dom操纵应该在指令中。在您的情况下,您将为JSTree创建一个指令。这个答案应该为您提供一个良好的开端:How to use jsTree events with AngularJS

要了解有关指令的更多信息,请参阅AngularJS的创建者:https://www.youtube.com/watch?v=WqmeI5fZcho(我将在某些时候制作AngularJS + TypeScript指令视频)

答案 3 :(得分:0)

正如其他人所建议的那样,你不应该自己这样做,棱角分明会自己做。

但是可以通过将$ scope作为字符串传递来完成,angular会为你做DI,所以你的代码看起来应该是这样的

var mc = new MyController("$scope"); 

答案 4 :(得分:0)

通常你会使用一个声明为参数的私有变量来保存注入的$ scope对象,如下所示:

&#13;
&#13;
..

class MyController {
  
  static $inject = ['$scope'];
  constructor(private scope: ng.IScope){
    this.init();  
  }
  
  private init() {
    this.scope.foo = 'bar';
  }
  
}

..
&#13;
&#13;
&#13;

尽管$ inject语句并不重要,但它明确声明$ scope是一个注入资产: - )

然后,您将以角度方式创建MyController的实例,如下所示:

&#13;
&#13;
angular.module('app')
  .controller('MyController', MyController);
&#13;
&#13;
&#13;