AngularJS + Coffeescript - 'Hello World'指令不起作用

时间:2013-11-15 19:28:41

标签: javascript angularjs coffeescript angularjs-directive

我不能让最简单的指令在我的AngularJS + Coffeescript项目中起作用。

我在directivesoffee中有这段代码:

'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>'

2 个答案:

答案 0 :(得分: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 :(得分:2)

你有一个错字:

restict: 'E'

应该是

restrict: 'E'

工作代码:http://plnkr.co/edit/8TifpS2EmYPLo4wl7YtK?p=preview