在AngularJS指令控制器中使用CoffeeScript的类

Gio*_*Gpx 2 coffeescript angularjs angularjs-directive

在使用CoffeeScript创建AngularJS指令时,我使用了这种方法:

angular
.module('MyApp', [])
.directive 'myDirective', ->
restrict: 'E'
controllerAs: 'ctrl'
controller: ->
  new class
    constructor: ->
      @value = 3
Run Code Online (Sandbox Code Playgroud)

此代码适用于Angular 1.2.14- jsbin,但不适用于1.3.0- jsbin.我在控制台中没有任何错误,只是它什么也没做.看起来控制器是一个空对象.

Mar*_*n K 5

我在这个帖子中回答了几乎相同的问题:AngularJS + Coffeescript - 'Hello World'指令不起作用.我喜欢将我的Angular对象保持为正确的CoffeeScript类.关键是将new 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)
Run Code Online (Sandbox Code Playgroud)

  • 好吧,我喜欢在类或者Angular模块中的所有内容,而不是两者的混合.因为我更愿意将控制器和服务编写为类,所以我希望将指令用于指令.一致性是王道 (3认同)