2

I can't make the simplest of directives work in my AngularJS + Coffeescript project.

I have this code in 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>'

And in my template, when I do

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

then the version number appears (0.1), showing that the first directive works properly, but the tag does not get replaced by anything.

Any idea what I did wrong?

I also tried this, which didn't work either:

# Hello world directive
app.directive 'hello', ->
    class Habit
        constructor: ->
            restict: 'E'
            template: '<div>Hello World</div>'
mascip
  • 1,347
  • 1
  • 14
  • 16

2 Answers2

7

You can also write your Angular Directive in CoffeeScript like this which I think is cleaner:

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)
Martin K
  • 782
  • 7
  • 13
  • 1
    do you have any examples of injecting services into a directive using this syntax? I like the style here (versus one we're using which uses an `@option` function to bootstrap the directive) but was struggling with adapting it on my own. – virtualandy Nov 05 '14 at 21:05
  • 2
    Hi @virtualandy. You can inject services like this: angular.module('my_module').directive 'MyDirective', ($http) -> new MyDirective($http) – Martin K Nov 07 '14 at 10:32
2

You have a typo:

restict: 'E'

should be

restrict: 'E'

Working code: http://plnkr.co/edit/8TifpS2EmYPLo4wl7YtK?p=preview

dfsq
  • 191,768
  • 25
  • 236
  • 258