2014-12-08 46 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