6

我正在尝试使用 Coffescript 类的 angularjs

我能够注入并能够使用咖啡脚本做一个成功的例子。但是要访问 $scope 我必须在构造函数中编写函数。我能做些什么来摆脱它。如果有另一种写法的好方法,请告诉我。

这是我的工作咖啡脚本代码

class PersonCtrl
    @$inject = ['$scope']

    constructor: (@scope) ->
        @scope.persons = [
            firstName:"Kunjan"
            lastName:"Dalal"
        ,
            firstName:"Kunj"
            lastName:"Dalal"
        ]

        @scope.addPerson = () =>
            @scope.persons.push angular.copy @scope.person 

如果需要任何进一步的细节,请告诉我。

4

1 回答 1

11

我使用了以下语法:

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

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

更新 @oto-brglez .bootstrap() 调用取代了 ng-app 在你的<html>标签上

更新 @TylerCollier,这是不久前的事了,现在我可能会使用Controller As表示法(或者可能是TypeScript!)

咖啡

class PetController 
    constructor: (@$scope) ->
        @pets = ['Fido','Felix']
    addPet: (pet) ->
        @pets.push(pet)

HTML

<div ng-controller="PetController as pc">
...
<li ng-repeat="pet in pc.pets">
于 2013-08-12T18:01:42.880 回答