2013-11-15 150 views
2

我無法在我的AngularJS + Coffeescript項目中使最簡單的指令工作。AngularJS + Coffeescript - 'Hello World'指令不起作用

我有這樣的代碼在directives.coffee:

'use strict' 
app_name = "myApp" 
app = angular.module "#{app_name}.directives", [] 

# Directive to include the version number of my project 
app.directive 'appVersion', [ 
'version', (version) -> 
    (scope, element, attrs) -> 
    element.text version 
] 

# Hello world directive 
app.directive 'hello',() -> 
    restict: 'E' 
    template: '<div>Hello World</div>' 

而且在我的模板,當我做

<span app-version></span> 
<hello></hello> 

然後出現版本號(0.1),顯示出第一個指令作品正確,但標籤不會被任何東西取代。

任何想法我做錯了什麼?

我也試過了,沒有工作之一:

# Hello world directive 
app.directive 'hello', -> 
    class Habit 
     constructor: -> 
      restict: 'E' 
      template: '<div>Hello World</div>' 

回答

7

你可以在這樣的CoffeeScript中寫下你的Angular Directive,我認爲它更清潔:

class MyDirective 
    constructor: (myService) -> 
     // Constructor stuff 
     @controller = MyController 
     @controllerAs = 'ctrl' 
    restrict: 'E' 
    replace: true 
    scope: 
     attributeStuff: '=' 
    link: (scope, element, attr) -> 

angular.module('my_module').directive 'MyDirective', (myService) -> 
    new MyDirective(myService) 
+1

你有任何使用這種語法將注入服務注入指令的例子嗎?我喜歡這裏的風格(與我們使用的風格相比,它使用'@ option'函數來啓動指令),但卻一直在努力適應自己的風格。 – virtualandy

+2

Hi @virtualandy。您可以注入這樣的服務:angular.module('my_module')。directive'MyDirective',($ http) - > 新的MyDirective($ http) –

+1

真棒,感謝您更新您的答案。 – virtualandy