2013-07-17 134 views
0

我有一個供應商:取消設置對象屬性

AdviceList.provider('$adviceList',function(){ 
    this.$get = function ($rootScope,$document,$compile,$http,$purr){ 

     function AdviceList(){ 

      $http.post('../sys/core/fetchTreatments.php').success(function(data,status){ 
       this.treatments = data; 
       console.log(this.treatments); // the correct object 
      }); 

      this.adviceCategories = [ 
       // available in the controller 
      ]; 

     } 
     return{ 

      AdviceList: function(){ 
       return new AdviceList(); 
      } 
     } 
    } 
}); 

而且,我有這個控制器:

AdviceList.controller('AdviceListCtrl',function($scope,$adviceList){ 
    var adv = $adviceList.AdviceList(); 
    $scope.treatments = adv.treatments; // undefined 
}); 

爲什麼,控制器的$scope.treatments撐不定,this.treatments但是供應商裏面,是正確填寫?另外,我的控制器中還有adviceCategories

回答

1

你得到的東西的調用本質上是異步的,所以當你試圖分配它們時,結果可能沒有被填充。

所以這裏

var adv = $adviceList.AdviceList(); 
$scope.treatments = adv.treatments; //The treatments would only get filled after the server call is over. 

你需要重寫代碼中,你把它分配給在成功回調的作用域屬性的一種方式。

+0

謝謝。你是否介意分享一個簡單例子的相關鏈接,如果你巧合的有一個? – user2422960

1

我會建議您簡化代碼

1)使用的角度,而不是供應商

2)簡單工廠方法返回一個承諾,以避免使用回調

AdviceList.service('adviceList', function ($http) { 
      return { 
       adviceList: function() { 
        return $http.post('../sys/core/fetchTreatments.php'); 
       } 
      } 
     }); 

     AdviceList.controller('AdviceListCtrl', function ($scope, $adviceList) { 
      adviceList.AdviceList().then(function (data) { 
       $scope.treatments = data //set value to data when data is recieved from server 
      }); 

     }); 
+0

謝謝。除了不太複雜的語法之外,您能簡單解釋一下選擇服務提供商的好處嗎?我會認爲使用提供者總是一個好主意,因爲他們是可配置的。 – user2422960

+0

提供商和服務類似,您可以使用任何服務。這裏的主要問題不是提供者vs服務,而是處理調用的異步性質。 @Ajay提出的建議會像魅力一樣工作。你可以看看這個問題的差異http://stackoverflow.com/questions/15666048/angular-js-service-vs-provide-vs-factory – Chandermani