Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs with Coffeescript class

I was trying angularjs with Coffescript class

I was able to inject and able to do a successful example using coffeescript. But to access $scope I have to write functions within the constructor. What I can do to get it out of it. If there is another good way to write that please let me know.

Here is my working coffeescript code

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 

Please let me know if any further details required.

like image 984
kunjee Avatar asked Aug 12 '13 09:08

kunjee


1 Answers

I have used the following syntax:

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

Take a look at this jsFiddle: http://jsfiddle.net/jwcMA/

UPDATE @oto-brglez the .bootstrap() call replaces having ng-app on your <html> tag

UPDATE @TylerCollier, this was a while back, now I would probably use the Controller As notation (or maybe TypeScript!)

COFFEE

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">
like image 98
malix Avatar answered Oct 30 '22 01:10

malix