【问题标题】:How to make sure that $scope.property has value before it is used如何确保 $scope.property 在使用前具有价值
【发布时间】:2017-04-02 20:41:00
【问题描述】:

我有一个带有两个 $scope 属性的 Angular 控制器:

 $scope.details = ortabilityService.detail();

 $scope.treeViewOptions = {           
            dataSource: new kendo.data.HierarchicalDataSource({
                data: $scope.details               
        };

正如我们所见,树视图选项取决于在将其用作数据源之前要解决的细节。现在,问题在于它是一个异步调用,并且始终不能保证在它在 treeviewOptions 中使用之前解决它。因此,它是一个非常不可靠的负载,它有时会加载,有时不会加载。如何确保 $scope.details 在用于 treeViewOptions 之前具有价值?

【问题讨论】:

    标签: javascript angularjs ajax asynchronous


    【解决方案1】:

    如果detail() 返回一个承诺,你可以这样做:

    ortabilityService.detail().then(function(result) {
      $scope.details = result;
    
      $scope.treeViewOptions = {           
        dataSource: new kendo.data.HierarchicalDataSource({
          data: $scope.details               
        })
      };
    });
    

    编辑

    正如 cmets 所指出的,ortabilityService.detail().$promise.then 在这种情况下有效。

    【讨论】:

    • 它给我一个错误,说 ortabilityService.detail().then i snot a function
    • 为了提供更多细节,我必须做一个小改动并执行 ortabilityService.detail().$promise.then 并且它起作用了。你可以相应地改变你的答案
    【解决方案2】:

    目标不是在你使用它之前确保它有一个值,而是确保当它得到它的值时,页面会更新。

    您可以使用手表或承诺来做到这一点。

    $scope.details = ortabilityService.detail();
    
    $scope.$watch('details', function(newValue, oldValue) {
      $scope.treeViewOptions = {           
            dataSource: new kendo.data.HierarchicalDataSource({
                data: newValue               
        };
    });
    

    【讨论】:

      【解决方案3】:

      我发现 angular kendo 非常适用于 promise: AngularJS : Where to use promises? 一些伪代码可能是:

      $scope.ctrl.details.$promise.then(function (results) {
      
         $scope.treeViewOptions = {           
                  dataSource: new kendo.data.HierarchicalDataSource({
                      data: results               
              };   
      }
      

      或者你可以加载剑道数据如

      var kendo_data_source = new kendo.data.DataSource();
      
      ...
      //after the promise is complete or data loads
      kendo_data_source.data(results) 
      

      【讨论】:

        【解决方案4】:

        考虑 ortabilityService.detail() 返回一个承诺

        ortabilityService.detail().then(
            function success(result){
                $scope.treeViewOptions = {           
                    dataSource: new kendo.data.HierarchicalDataSource({
                        data: result              
                    });
            }, 
            function error(result){
                //when it fails to load
            }
        );
        

        【讨论】:

          猜你喜欢
          • 2010-12-03
          • 1970-01-01
          • 1970-01-01
          • 2020-07-05
          • 1970-01-01
          • 1970-01-01
          • 2016-01-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多