2014-12-08 43 views
0

下面是代碼:

var app = angular.module('componentsApp', []); 

app.directive('components', ["$http", function($http) { 
    return { 
     restrict: 'E', 
     templateUrl: "component.html", 
     controller: function() { 
      this.heading = "Available Data"; 
      this.results= []; 

      $http.get("data.json").success(function(data) { 
       this.results = data; 
      }); 
     }, 
     controllerAs: 'component' 
    }; 
}]); 

Components.html

<h3>{{ component.heading }}</h3> 
<div ng-repeat="result in component.results"> 
    <span>{{ result.name }}</span> 
    <span>{{ result.description }}</span> 
</div> 

當我運行它時,圖標變顯示爲空。我想這與自$ http調用使用promises以後指令構造元素時存在的數據問題有關。

任何人都可以證實這一點嗎?如果是這樣,解決方案是什麼?

+0

你可以添加component.html的相關部分?另外,什麼是'圖標'變量? – 2014-12-08 06:46:09

+0

如何在您的$ http中訪問外部此上下文.... – Akilan 2014-12-08 07:02:52

回答

3

問題是當你這樣做時:this.results = data;回調$http,這不是指你的控制器,而是指回調範圍。所以,你可以嘗試這樣的事:

app.directive('components', ["$http", function($http) { 
    return { 
     restrict: 'E', 
     templateUrl: "component.html", 
     controller: function() { 
      var vm = this; 
      vm.heading = "Available Data"; 
      vm.results= []; 

      $http.get("data.json").success(function(data) { 
       vm.results = data; 
      }); 
     }, 
     controllerAs: 'component' 
    }; 
}]); 
+0

謝謝!這沒有竅門:) – 2014-12-09 00:17:17

相關問題