2015-11-30 58 views
0

我試圖創建一個指示採用了棱角分明1.5.0-β2在指令採用了棱角分明

我想使用該指令一個HTTP請求,將數據粘貼到視圖。通常它使用$ scope完成,但似乎我不能在指令中使用$ scope。

這是我到目前爲止的代碼:

app.directive('latestDrinks', ['ParseGlobalImageIdService',function (ParseGlobalImageIdService) { 
    return { 
     restrict: 'E', 
     templateUrl: 'views/latest-drinks.html', 
     controller: ['$http','$scope', function($http,$scope) { 
      $scope.latestDrinksRows = $http({ 
       method: 'GET', 
       url: 'http://api.myalcoholist.com:8888/cocktail/get_latest_drinks' 
      }).then(function successCallback(response) { 
       response.data.forEach(function (element, index, array) { 
        element.global_image_id = ParseGlobalImageIdService.thumb(element.global_image_id); 
       }) 
       return response.data; 
      }, function errorCallback(response) { 
       alert('error'); 
       return null; 
      }); 
     }], 
    }}]); 

,你可以在返回的對象的控制特性看,我嘗試注入$ http和$範圍。並使用$ scope來設置latestDrinksRows以便能夠在視圖中使用它。

說我遇到的問題是,當我嘗試打印變量視圖

{{latestDrinksRows}} 

我得到一個空的對象。

我用鉻檢查器檢查和http請求正在正確發送和有效的json數據返回。

我也google了很多,我注意到沒有人真的試圖擴大$ scope在控制器屬性,所以我猜我缺少的東西。

有關該問題的任何信息將不勝感激。

回答

4

您沒有正確使用$ http。目前要傳遞一個承諾到$ scope變量,而你要分配的$ HTTP調用該變量,這將需要像下面

 $http({ 
      method: 'GET', 
      url: 'http://api.myalcoholist.com:8888/cocktail/get_latest_drinks' 
     }).then(function successCallback(response) { 
      response.data.forEach(function (element, index, array) { 
       element.global_image_id = ParseGlobalImageIdService.thumb(element.global_image_id); 
      }) 
      // ************************ 
      $scope.latestDrinksRows = response.data; 

     }, function errorCallback(response) { 
      alert('error'); 
      return null; 
     }); 
0

您將範圍變量設置爲$http的返回值,這僅僅是一個承諾。您需要在.then處理函數中設置所需的數據,這是您獲取HTTP響應的地方。

0

一個範圍添加到您的指令的結果:

app.directive('latestDrinks', ['ParseGlobalImageIdService',function (ParseGlobalImageIdService) { 
    return { 
     restrict: 'E', 
     scope: { 
      param: '=' 
     } 
     ... 
    }}]); 

而在你的視圖中添加的「參數」屬性的元素:

<latestDrinks param="myModel"></latestDrinks> 

而不是基於myModel把你的目標你想與你的指令來分享你添加它在你的指導功能的參數中:

controller: ['$http','scope', function($http,scope) { 
      $http({ 
       method: 'GET', 
       url: 'http://api.myalcoholist.com:8888/cocktail/get_latest_drinks' 
      }).then(function successCallback(response) { 
       scope.param = response 
      }); 
     }],