2

我正在使用 angularjs 和 firebase 上传文件我正在尝试将参数从控制器传递到 state_changed 事件中查看它不工作,我可以在控制器上打印它但不能将它用于视图

我使用的这些代码

// File or Blob named mountains.jpg
var file = "";

// Create the file metadata
var metadata = {
  contentType: 'image/jpeg'
};

// Upload file and metadata to the object 'images/mountains.jpg'
var uploadTask = storageRef.child('images/' + file.name).put(file, metadata);

// Listen for state changes, errors, and completion of the upload.
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
  function(snapshot) {
    // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
    var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    console.log('Upload is ' + progress + '% done');
    $scope.progress = progress;
    switch (snapshot.state) {
      case firebase.storage.TaskState.PAUSED: // or 'paused'
        console.log('Upload is paused');
        break;
      case firebase.storage.TaskState.RUNNING: // or 'running'
        console.log('Upload is running');
        break;
    }
  }, function(error) {
  switch (error.code) {
    case 'storage/unauthorized':
      // User doesn't have permission to access the object
      break;

    case 'storage/canceled':
      // User canceled the upload
      break;

    ...

    case 'storage/unknown':
      // Unknown error occurred, inspect error.serverResponse
      break;
  }
}, function() {
  // Upload completed successfully, now we can get the download URL
  var downloadURL = uploadTask.snapshot.downloadURL;
});
<pre>{{progress}}</pre>

4

1 回答 1

1

因为 firebase 事件发生在 AngularJS 框架之外,所以对 $scope 的更改需要使用$scope.$apply()

$scope.$apply(function() {
    $scope.progress = progress;
});

从文档:

Angular 通过提供自己的事件处理循环来修改正常的 JavaScript 流程。这将 JavaScript 拆分为经典和 Angular 执行上下文。只有在 Angular 执行上下文中应用的操作才能从 Angular 数据绑定、异常处理、属性监视等中受益……您使用$apply()从 JavaScript 进入 Angular 执行上下文。

请记住,在大多数地方(控制器、服务)$apply已经由处理事件的指令为您调用。$apply仅在实现自定义事件回调或使用第三方库回调时才需要显式调用。

有关详细信息,请参阅

于 2017-02-28T20:19:44.530 回答