【问题标题】:AngularJS + Coffeescript - 'Hello World' directive not workingAngularJS + Coffeescript - 'Hello World' 指令不起作用
【发布时间】:2013-11-29 07:37:19
【问题描述】:

我无法在我的 AngularJS + Coffeescript 项目中使用最简单的指令。

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

【问题讨论】:

    标签: javascript angularjs coffeescript angularjs-directive


    【解决方案1】:

    您也可以像这样在 CoffeeScript 中编写 Angular 指令,我认为这样更简洁:

    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)
    

    【讨论】:

    • 你有使用这种语法将服务注入指令的例子吗?我喜欢这里的风格(与我们使用的使用 @option 函数来引导指令的风格相比),但我自己在努力适应它。
    • 嗨@virtualandy。您可以像这样注入服务: angular.module('my_module').directive 'MyDirective', ($http) -> new MyDirective($http)
    【解决方案2】:

    你有一个错字:

    restict: 'E'
    

    应该是

    restrict: 'E'
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多