【问题标题】:Can't reassign variable in CoffeeScript无法在 CoffeeScript 中重新分配变量
【发布时间】:2015-01-16 18:31:57
【问题描述】:

我是 CoffeeScript 新手并尝试编写 Angular 控制器。但是,我认为我在变量范围界定方面存在问题。我的代码如下:

app.controller 'IndexController', ['$scope', 'Authentication', 'Items', 'Snackbar', ($scope, Authentication, Items, Snackbar) ->
    activate = ->
        itemsSuccessFn = (data, status, headers, config) ->
            vm.items = data.data
            return

        itemsErrorFn = (data, status, headers, config) ->
            Snackbar.error data.error
            return

        Items().all().then itemsSuccessFn, itemsErrorFn
        return

    vm = this
    vm.items = []
    vm.isAuthenticated = Authentication.isAuthenticated()
    activate()
    return
]

问题出在 items 变量上。在activate 中运行itemsSuccessFn 时,该变量将填充来自服务的数据。但在主范围内,变量再次为空。我究竟做错了什么?我该如何解决?

如果还有关于代码的任何其他内容,应该做得更好,请告诉我,因为正如我所提到的,我刚刚开始学习。

【问题讨论】:

  • in the main scope the variable is again empty 是什么意思?您是否使用“控制器作为”语法?示例:ng-controller="IndexController as vm"?

标签: angularjs coffeescript


【解决方案1】:

不用声明局部变量,直接引用$scope即可。

app.controller 'IndexController', ['$scope', 'Authentication', 'Items', 'Snackbar', ($scope, Authentication, Items, Snackbar) ->
    activate = ->
        itemsSuccessFn = (data, status, headers, config) ->
            $scope.items = data.data
            return

        itemsErrorFn = (data, status, headers, config) ->
            Snackbar.error data.error
            return

        Items().all().then itemsSuccessFn, itemsErrorFn
        return

    $scope.items = []
    $scope.isAuthenticated = Authentication.isAuthenticated()
    activate()
    return
]

但是,如果您使用controllerAs 语法,则必须使用粗箭头保持对this 的正确引用。这样一来,您就不需要 vm 变量了。

app.controller 'IndexController', ['$scope', 'Authentication', 'Items', 'Snackbar', ($scope, Authentication, Items, Snackbar) ->
    activate = =>
        itemsSuccessFn = (data, status, headers, config) =>
            @items = data.data
            return

        itemsErrorFn = (data, status, headers, config) ->
            Snackbar.error data.error
            return

        Items().all().then itemsSuccessFn, itemsErrorFn
        return

    @items = []
    @isAuthenticated = Authentication.isAuthenticated()
    activate()
    return
]

【讨论】:

  • 好的,我明白了。但是,即使我已经完成了您的建议,并在激活后尝试console.log @items,数组仍然是空的。它也没有在模板中呈现,在另一个 ItemsController 的行 $scope.$watchCollection( -> $scope.items ) render 处给出错误 TypeError: Cannot read property 'length' of undefined。我现在该怎么办?
  • @Marcin 您可以将遇到问题的新代码添加到原始问题中吗?您似乎在创建 items 之前声明了 watch
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-26
  • 2017-05-02
  • 1970-01-01
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
相关资源
最近更新 更多