当在函数内部分配$ scope值时,数据绑定不起作用

时间:2017-09-05 11:22:23

标签: javascript angularjs promise

任何人都可以帮助我找出我在这里做错了什么。我正在调用 $ http服务上传.xlsx文件,然后将函数i分配给 $ scope variable 并尝试绑定它在HTML中但绑定没有发生。任何建议都会提前感谢。

这是代码示例。

fileUpload.uploadFile(file)
     .then(function(response) {
          console.log('File Uploaded Successfully');
            if (response.status == 201) {
                if(response.data!=undefined) {
                    var _data = angular.fromJson(response.data);
                        $scope.batchUploadDetails = _data;
                        console.log($scope.batchUploadDetails);
                    }
                }
      }, function(response) {
        $scope.batchUploadDetails = {};
        console.log('File Uploading Failed!');
});

Html模板

<div class="col-xs-12 no_pad borderAll padding20 margTop20 mb20" >

    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-12 no_pad">
        <label class="col-xs-12 no_pad labelNew">Employee count</label><span
                    class="col-xs-12 no_pad">{{ batchUploadDetails.employeeCount }}</span>
    </div>

    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-12 no_pad">
        <label class="col-xs-12 no_pad labelNew">Company code</label><span
                    class="col-xs-12 no_pad">{{ batchUploadDetails.companyCode }}</span>
    </div>

</div>

2 个答案:

答案 0 :(得分:0)

您可以使用$ apply来触发$ digest循环。

fileUpload.uploadFile(file)
     .then(function(response) {
          console.log('File Uploaded Successfully');
            if (response.status == 201) {
                if(response.data!=undefined) {
                    var _data = angular.fromJson(response.data);
                        $scope.batchUploadDetails = _data;
                        setTimeout(function (){ 
                           $scope.$apply();// you can use $timeout as well. Here I used settimeout to avoid $digest already in progress error
                      },0)
                        console.log($scope.batchUploadDetails);
                    }
                }
      }, function(response) {
        $scope.batchUploadDetails = {};
        console.log('File Uploading Failed!');
});

答案 1 :(得分:0)

您应该在$ apply中修改范围变量,以使更改生效。

您还可以使用$ timeout服务,最终将调用$ apply服务。