Angularjs与Coffeescript类的结合

6

我尝试使用Coffescript类来使用angularjs

我能够注入并成功地使用coffeescript完成一个示例。但是要访问$scope,我必须在构造函数内编写函数。有什么办法可以将其移出构造函数?如果有其他更好的编写方式,请告诉我。

以下是我的工作中的coffeescript代码

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 

如果需要更多细节,请告诉我。

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() 调用替代了在<html>标签上使用ng-app。

更新 @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">

好的,所以我在构造函数中缺少范围注册。感谢这个东西至少对JavaScript有意义。 - kunjee
1
@malix,你能解释一下最后一行的目的吗? - Oto Brglez
对于您想要添加的每个方法,您还必须在构造函数中进行映射吗?@scope.clearText = @clearText - Tyler Collier
1
@TylerCollier,这是一段时间以前的事情了,现在我可能会使用Controller As符号,或者更好的是TypeScript :) - malix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接