2016-02-29 131 views
0

我想弄清楚如何在TypeScript中使用AngularJS中的指令。我跟着一个教程,在那里我相应地跟着每一步......但是我遇到了一些麻烦。由于某种原因,它没有显示我的指令的内容。AngularJS指令(TypeScript)

指令本身:

module Directives { 
    debugger; 
    export interface IMyScope extends ng.IScope 
    { 
     name: string; 
    } 

    export function LeftMenu(): ng.IDirective { 
     return { 
      template: '<div>{{name}}</div>', 
      scope: {}, 
      link: (scope: IMyScope) => { 
       scope.name = 'Aaron'; 
      } 
     }; 
    } 
} 

现在,我把一个调试器来检查我的代码甚至可以运行,直到它到达指令,是的是的。我的Chrome正在调试它应该达到的程度。

注册的所有指令(即使我只有一个大气压):

/// <reference path="../reference.ts" /> 

angular.module('directives', []).directive(Directives) 

我的参考文件:

/// <reference path="../wwwroot/libs/bower_components/definitelytyped/angularjs/angular.d.ts" /> 
/// <reference path="../wwwroot/libs/bower_components/definitelytyped/angularjs/angular-route.d.ts" /> 
/// <reference path="../wwwroot/libs/dx-libs/ts/dx.all.d.ts" /> 

/// <reference path="contollers/controllers.ts" /> 
/// <reference path="directives/directives.ts" /> 
/// <reference path="app.ts" /> 

调用这样的指令:

<div> 
    <left-menu></left-menu> 
</div> 

有没有错误记录什么,所以永远..所以,我希望有人有这个问题的解决方案。

在此先感谢!

+0

'angular.module('directives',[])。directive(Directives)'不认为这段代码可以工作。你注册一个打字稿模块,没有任何名字 – devqon

+0

@devqon我正在为我的控制器做这件事,它工作。另外,调试器在我的浏览器中开始调试。所以这意味着它至少会进入模块。 – Peurr

回答

1

您必须注册一个名称为第一个参数的指令。这是我会怎么写你的指令结合打字稿:

export = class LeftMenu implements angular.IDirective { 
    static ID = "leftMenu"; 

    public restrict = "AE"; 
    public template = '<div>{{name}}</div>'; 
    public scope = {}; 
    public link = (scope: IMyScope) => { 
     scope.name = 'Aaron'; 
    } 

    // to show how to handle injectables 
    constructor(private somethingInjected){} 

    static factory() { 
     // to show how to handle injectables 
     var directive = (somethingInjected) => new MyDirective(somethingInjected); 
     directive.$inject = ["somethingInjected"]; 
     return directive; 
    } 
} 

,并进行注册:

import leftMenu = require("LeftMenu"); 

angular.module('directives', []).directive(leftMenu.ID, leftMenu.factory()); 
+0

对不起,迟到的回应。我认为你的脚本正在工作,但我仍然无法看到我的页面上显示的指令。我会怎么做?我虽然''将是技巧,但不是.. @devqon – Peurr

+0

你在你的模块中包含'directives'模块吗?:angular.module(“myModule”,[“directives”]) ;' – devqon

+0

这就是我所做的:https://gyazo.com/9a054867e9f2095637e1e664ad17a791 – Peurr

0

调试器的火灾,因为你确实提交对象.directive(打字稿transpiles模块成对象默认)。

您可以尝试直接在文件中初始化指令declarating它:

angular 
    .module("module.a") 
    .directive("directive.a",(): angular.IDirective => 
    { 
     return { 
      restrict: "E", 
      templateUrl: "template.a.html", 
      controller: "controller.a", 
      controllerAs: "$ctrl", 
      link:() => {}, 
      bindToController: true 
     }; 
    }); 

或简单地导出函数

angular 
    .module("module.a") 
    .directive("directive.a", Directives.LeftMenu); 

我不知道的打字稿模块识别版本的角度函数.directive,该函数注册模块的所有指令。