Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于CoffeeScript类的AngularJS控制器';t更新模板_Angularjs_Coffeescript - Fatal编程技术网

基于CoffeeScript类的AngularJS控制器';t更新模板

基于CoffeeScript类的AngularJS控制器';t更新模板,angularjs,coffeescript,Angularjs,Coffeescript,在CoffeeScript中使用AngularJS 1.1.5,我尝试使用新的“控制器作为…”语法,如下所示: class EventCtrl @$inject = ['$scope', '$http'] constructor: (@$scope, @$http) -> @$http.get('/some/url/', config) .success (data) -> #set the e

在CoffeeScript中使用AngularJS 1.1.5,我尝试使用新的“控制器作为…”语法,如下所示:

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>
解决方案
success
处理程序使用粗箭头。构造函数会自动附加到实例,因此那里不需要胖箭头(如果它不是构造函数的话,就会是胖箭头)


您应该将它附加到
范围
,而不是
@
(如果
.success
更改了上下文,它甚至可能不是您的类实例。您可以使用coffeescript的胖箭头来实现这一点)


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

通常您会将其作为实例属性,但实际上,
http.get
中的
@
似乎不是类而是窗口。解决方案是在方法的开头明确地将
@
设置为实例。哦,是的,你确实是对的,没有必要使用
init()
,这是一个遗留问题,因为我剥离了很多其他代码。正如我所说,你可以使用CoffeeScript的
=>
(胖箭头)来保持你的
这个
你不能在构造函数上使用胖箭头(
不能将构造函数定义为绑定函数
),但在
success
处理程序上使用它确实解决了这个问题。谢谢我真的想在成功处理器上使用它。
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!')
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!')