angular ui-router $ state.reload()在文件上传后无法更新范围变量

时间:2016-09-21 05:47:59

标签: javascript angularjs coffeescript

我正在使用angular-file-upload上传文件,而我正在尝试

  1. 重新加载状态,并在上传完成后全部解决
  2. 然后更新范围变量以在模板上显示消息
  3. 这是我的代码

    $scope.upload.success = false
    
    $scope.uploader = new FileUploader(
        headers: headers    
        url: url
        )
    
    $scope.uploadFile = ->
        queue = $scope.uploader.queue
        last_item = queue[queue.length-1]
        if last_item != undefined
          $timeout(->
            last_item.upload()
          , 3000)
        else
          $scope.nofile = true
          Flash.create('warning', 'Please select an excel file to upload')
    
    $scope.uploader.onSuccessItem = (item, response, status, headers) ->
        Flash.create('success', response.message)
        ################
        $state.reload()
        $scope.upload.success = true
        ################
    

    $ state.reload()返回true后运行console.log($ scope.upload.success),但视图上的$ scope.upload.success仍为false。如何更改视图的范围?

1 个答案:

答案 0 :(得分:-1)

基本上这与Angular没有意识到onSuccessItem内发生的变化有关。

一种解决方案是将必要的代码包装在$ apply方法中:

$scope.uploader.onSuccessItem = (item, response, status, headers) ->
    Flash.create('success', response.message)
    ################
    $state.reload()
    $scope.$apply(() -> 
      $scope.upload.success = true
    )
    ################

另一个解决方案是替换回调并调用$ scope。$ apply();

$scope.uploader.onSuccessItem = (item, response, status, headers) ->
    Flash.create('success', response.message)
    ################
    $state.reload()
    $scope.upload.success = true
    $scope.$apply()
    ################

注意:我不熟悉CoffeeScript(或其他语法)。