2016-01-22 26 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