使用"Coffee Script Class"而不是Method作为Angular JS ng-controller

Mar*_*lho 2 controller class coffeescript angularjs

我想做一些我认为使用"Coffee Script Class"和Angular JS结构的好方法.

<!doctype html>
<html ng-app>

  <head>
    <meta charset=utf-8>
    <meta name=viewport content="width=device-width, initial-scale=1">
    <title>Main Test</title>
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <script type="text/javascript" src="js/coffee.js"></script>
  </head>

  <body>
    <div ng-controller="MainClass" style="margin-left:10px">
      <h2>All todos: {{test()}}</h2>
    </div>
  </body>

</html>
Run Code Online (Sandbox Code Playgroud)

请注意,我将DIV ng-controller设置为MainClass并在H2 HTML标记内设置绑定test()方法.

class AngularJSController
  constructor: ($scope, $main) ->

    $scope.test = MainClass.prototype.test
    MainClass.test = MainClass.prototype.test
    $main.test = MainClass.prototype.test
    test = MainClass.prototype.test
    @test = MainClass.prototype.test

    console.log @test

class MainClass extends AngularJSController
  constructor: ($scope) ->
    super $scope, this

    setTimeout (->
        console.log test()
      ), 1000

    test();

  test: -> 'aloha!'
Run Code Online (Sandbox Code Playgroud)

在AngularJSController构造函数中,我尝试了所有我想象的形式在MainClass范围内设置我的超类方法TEST而没有成功.

我正在尝试这样做,因为我想在我的Angular JS控制器和组件上使用类.

我已经陷入的问题:

  1. 如果我尝试使用@test()而不是test()在setTimeout内部,jQuery已经用this一种JQuery Window Object 替换了该属性.

    setTimeout (-> console.log @test()), 1000
    
    Run Code Online (Sandbox Code Playgroud)
  2. 我不知道究竟是什么test()电话的范围,如果这个地方(或@导致咖啡),不是一样的地方.

    test() != this.test() != @.test() # the first scope isn't the same scope of last two calls
    
    Run Code Online (Sandbox Code Playgroud)

mal*_*lix 8

我使用了以下语法:

app = angular.module 'myapp', []

class MySimpleCtrl

  @$inject: ['$scope'] 
  constructor: (@scope) ->
    @scope.demo = 'demo value'
    @scope.clearText = @clearText

  clearText: =>
    @scope.demo = ""

app.controller 'MySimpleCtrl', MySimpleCtrl

angular.bootstrap document, ['myapp']
Run Code Online (Sandbox Code Playgroud)

看看这个jsFiddle:http: //jsfiddle.net/jwcMA/