2014-06-18 2 views
3

서비스에서 데이터를로드하고 $ q를 사용하여 뷰를 업데이트하려고하는데 작동하지 않습니다. 컨트롤러 내부에 http 호출을 넣으면 작동하지만 서비스의 일부가되기를 원합니다.

어떤 도움이 필요합니까? 또한, 약속 대신에 이것을하는 더 좋은 방법이 있습니까?

아래의 데모 및 코드.

---------- Fiddle Demo Link ----------

보기

<div ng-init="getData()"> 
    <div ng-repeat="item in list">{{item.name}}</div> 
</div> 

컨트롤러

.controller('ctrl', ['$scope', 'dataservice', '$q', function ($scope, dataservice, $q) { 

    $scope.list = dataservice.datalist; 

    var loadData = function() { 
    dataservice.fakeHttpGetData(); 
    }; 

    var setDataToScope = function() { 
    $scope.list = dataservice.datalist; 
    }; 

    $scope.getData = function() { 
    var defer = $q.defer(); 
    defer.promise.then(setDataToScope()); 
    defer.resolve(loadData()); 
    }; 

}]) 

서비스

.factory('dataservice', ['$timeout', function ($timeout) { 

    // view displays this list at load 
    this.datalist = [{'name': 'alpha'}, {'name': 'bravo'}]; 

    this.fakeHttpGetData = function() { 
    $timeout(function() { 

     // view should display this list after 2 seconds 
     this.datalist = [{'name': 'charlie'}, {'name': 'delta'}, {'name': 'echo'}]; 
    }, 
    2000); 
    }; 

    return this; 
}]); 

답변

1

ngInit 또는 $ q가 필요하지 않습니다. 이것이 당신이 어떻게 해야하는지입니다.

dataservice.list도 컨트롤러에 노출 시켜서는 안됩니다. 컨트롤러는 기존 목록을 보내거나 목록을 업데이트 한 다음 보낼지 여부를 결정하는 논리의 대부분을 담고있는 dataservice에 비공식적이어야합니다.

angular.module('app', []) 

     .controller('ctrl', ['$scope', 'dataservice', function ($scope, dataservice) { 

      loadData(); 

      function loadData() { 
       dataservice.fakeHttpGetData().then(function (result) { 
        $scope.list = result; 
       }); 
      } 
     }]) 

     .factory('dataservice', ['$timeout', function ($timeout) { 

      var datalist = [ 
       { 
        'name': 'alpha' 
       }, 
       { 
        'name': 'bravo' 
       } 
      ]; 

      this.fakeHttpGetData = function() { 

       return $timeout(function() { 

          // Logic here to determine what the list should be (what combination of new data and the existing list). 

          datalist = [ 
           { 
            'name': 'charlie' 
           }, 
           { 
            'name': 'delta' 
           }, 
           { 
            'name': 'echo' 
           } 
          ]; 

          return datalist; 
         }, 
         2000); 
      }; 

      return this; 
     }]); 
1

먼저, ng-init을 이런 식으로 사용하지 마십시오. 워드 프로세서에 따라 아래 데모에서 볼 수 있듯이

ngInit의 유일한 적절한 사용은 ngRepeat의 특별한 속성 별명입니다. 이 경우 외에 은 ngInit 대신 컨트롤러를 사용하여 범위의 값을 초기화해야합니다.

둘째, 약속이 경우에 사용할 수있는 완벽한 것은 있지만, $http 전화가 당신을 위해 약속을 반환대로, $q 접촉 할 필요가 없습니다. 당신이 컨트롤러 내부

this.getDataFromService = function() { 
    return $http(/* http call info */); 
}; 

다음 :

단순히 서비스에서 $http 결과를 반환, 제대로 이렇게하려면 http://jsfiddle.net/RgwLR/

:

dataservice.getDataFromService().then(function(result){ 
    $scope.list = result.data; 
});  

을 또한 여기에 업데이트 된 바이올린입니다 $q.when()은 약속의 주어진 값을 단순히 랩핑합니다 (의 응답을 모방합니다.) 귀하의 예에서).

+0

IIRC,'는 HTTP의 .then' 요청 자체가, 당신은 –

+0

result.data'없이 바이올린에서 잘 작동하는 것 같다'원하는'예 –

+0

을 .data'의 결과지만, 바이올린은 HTTP 요청을하지 않습니다. :) –