6

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.

1 Answer 1

11

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">
Sign up to request clarification or add additional context in comments.

4 Comments

Okies, So, I was missing registering of scope in constructor. Thanks that thing make sense at least for javascript.
@malix could you please explain the propose of last line?
For each method you want to add, you have to also map it in the constructor? @scope.clearText = @clearText
@TylerCollier, this was a while back, now I would probably use the Controller As notation, or better yet, TypeScript :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.