【问题标题】:CoffeeScript class-based controller for AngularJS doesn't update templateAngularJS 的 CoffeeScript 基于类的控制器不更新模板
【发布时间】:2013-11-01 09:15:09
【问题描述】:

在 CoffeeScript 中使用 AngularJS 1.1.5 我正在尝试使用新的“Controller as ...”语法,如下所示:

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)

使用以下 HTML 片段:

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

除了@events 中的更改不会更新模板(中的绑定点)之外,这一切正常。 @$http.getsuccess 处理程序中传入的“数据”看起来没问题。

这段代码一直在使用带有常规非类控制器的以前版本的 AngularJS。

更新 一个(丑陋的)解决方案是在方法中将this@)显式设置为本地值(下例中的thiz)。不是很优雅,但很有效。

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!')

解决方案success 处理程序使用粗箭头。构造函数会自动附加到实例上,因此那里不需要粗箭头(如果它不是构造函数,它会是这样)。

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!')

【问题讨论】:

    标签: angularjs coffeescript


    【解决方案1】:

    你应该把它附加到scope,而不是@(如果.success改变了上下文,它甚至可能不是你的类实例。你可以使用coffeescript的胖箭头)。

    另外,使用init 方法有什么意义?这正是构造函数的目的。

    【讨论】:

    • 通常您会将其设为实例属性,但实际上http.get 中的@ 似乎不是类而是窗口。一种解决方案是在方法开始时将@ 显式设置为实例。哦,是的,你确实是对的,不需要init(),这是一个遗留问题,因为我剥离了很多其他代码。
    • 正如我所说,您可以使用 CoffeeScript 的 =&gt;(粗箭头)来保留您的 this
    • 您不能在构造函数 (cannot define a constructor as a bound function) 上使用粗箭头,但在 success 处理程序上使用它确实可以解决问题。谢谢!
    • 我确实打算在成功处理程序上使用它。
    猜你喜欢
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 2018-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多