Berco Beute
Berco Beute

Reputation: 1195

CoffeeScript class-based controller for AngularJS doesn't update template

Using AngularJS 1.1.5 with CoffeeScript I'm trying the use the new 'Controller as ...' syntax as follows:

class EventCtrl
    @$inject = ['$scope', '$http']

    constructor: (@$scope, @$http) ->
        @$http.get('/some/url/', config)
            .success (data) ->
                #set the events directive
                @events = data
            .error (data) ->
                console.log('error!')

app.controller('EventCtrl', EventCtrl)

With the following HTML fragment:

<div ng-controller="EventCtrl as ctrl">
    <div>{{ctrl.events}}</div>
</div>

This works alright except for the fact that changes in @events don't update (the binding point in) the template. The 'data' incoming in the success handler of the @$http.get is looking ok.

This code has been working with a previous version of AngularJS with the regular none-class controllers.

UPDATE One (ugly) solution turns out to be explicity setting this (@) to a local value in the method (thiz in the example below). Not very elegant but it works.

class EventCtrl
    @$inject = ['$scope', '$http']

    constructor: (@$scope, @$http) ->
        thiz = @
        @$http.get('/some/url/', config)
            .success (data) ->
                #set the events directive
                thiz.events = data
            .error (data) ->
                console.log('error!')

SOLUTION Use a fat arrow for the success handler. The constructor is automatically attached to the instance so a fat arrow is not needed there (it would have been if it weren't a constructor).

class EventCtrl
    @$inject = ['$scope', '$http']

    constructor: (@$scope, @$http) ->
        @$http.get('/some/url/', config)
            .success (data) =>
                #set the events directive
                @events = data
            .error (data) ->
                console.log('error!')

Upvotes: 1

Views: 1163

Answers (1)

Ven
Ven

Reputation: 19039

You're supposed to attach it to scope, not @ (which might not even be your class instance, if .success changes the context. You can use coffeescript's fat arrow for that).

Also, what's the point of having an init method ? It's exactly the constructor's purpose.

Upvotes: 2

Related Questions