2016-01-22 80 views
0

在我的控制器的$ scope中,我有一个名为myObject的对象,它将被$ http.get(...)填充。

angular.module('myApp').controller('myController', ['$scope', function($scope) { 

    this.myObject={}; //object to be loaded by $http.get 

    //We initiate the request to load myObject. 
    $http({ 
     url: '/myurl', 
     method: 'GET' 
    }).then(function(result){ 
      this.myObject = result.data; 
    }, function(data, status){}); 

}]); 

在HTML视图,有很多依赖于myObject的指令,并且将返回错误,如“无法读取属性空的‘XXX’”如果在$ http.get返回前运行一个回应。

你会如何去暂停在this.myObject加载之前运行的指令?

+0

它取决于指令如何使用数据。如果你也发布了指令代码,会很好。 – Subash

回答

2

您可以通过用ng-if包装它来延迟执行指令。你可以做下面的事情。

HTML:

<div ng-if="vm.loadingComplete"> 
    <your-directive your-data="vm.myObject"></your-directive> 
</div> 

JS:

angular.module('myApp').controller('myController', ['$scope', function($scope) { 
    var vm = this; 

    // notice I have create variable vm and cached this 
    // if not done so, you cannot use this.something inside nested functions 
    // as this would mean something else there 

    vm.myObject={}; //object to be loaded by $http.get 
    vm.loadingComplete = false; 

    //We initiate the request to load myObject. 
    $http({ 
     url: '/myurl', 
     method: 'GET' 
    }).then(function(result){ 
     // you had a issue here before 
     // this.myObject is not same as this.myObject outside this function 
     vm.myObject = result.data; 
     vm.loadingComplete = result; 
    }, function(data, status){}); 
}]); 
1

假设你的指令是 'TESTDIR',

app.directive('testDir', function(){ 
return { 
      restrict: "AE", 
      transclude: true, 
      replace: false, 
      //templateUrl: "/views/api_status_chart.html", 
      scope: { 
       myData: '=' // this is your data from the controller 
      }, 
      link: function (scope, element, args) { 

        initializeDirective function(){ 
         // wrap all your functionality inside this function 
        } 

        scope.$watch('myData', function(newVal){ 
         // if new value is not null do your all computation 
         if(newVal != null && newVal.length > 0){ 
           initializeDirective(); 
         } 
        }); 
      } 
}); 

<test-dir my-data="myObject "> </test-dir> 

概念

只有当数据不为空时,才能执行所有功能。否则什么都不要做

0

使用ngIf指令,它使用角度js并在使用它之前验证html模板中的myObject

`<div ng-if="myObject!=== null"> <!-- set myObject = null by default in controller --> 
    <!-- use myObject's values to generate DOM --> 
</div>` 

由于在双向绑定,只要myObject被设置为一个值的角度作品,角将评估在HTML模板ng-if指令。

ngIf - directive in module ng