2016-11-27 2 views
0

내 응용 프로그램 컨트롤러에서 내 API에 요청합니다. 그것은 다음과 같습니다각도 js에서 d3으로 json을 전달하는 방법은 무엇입니까?

.state('state1', { 
     url: '/datas/:id', 
     templateUrl: 'myurl.com', 
     title: 'title', 
      controller: function($http, $rootScope, $location, $stateParams){ 
       var id = $stateParams.id;    
     $http.post('http://' + $location.host() + id, {id: id } , {}) 
     .then(function(d){ 

      $rootScope.data = d.data; 
     }, 
     function(err){ 
      console.log(err); 
     }); 
     }, 
    }) 

내 D3 스크립트는 다음과 같이이다 :

<script> 
 
    ... 
 
    var force = d3.layout.force().size([width, height]).on("tick", tick); 
 

 
    var svg = d3.select("#d3g").append("svg").attr("width", width).attr("height", height); 
 
    var link = svg.selectAll(".link"), 
 
     node = svg.selectAll(".node"); 
 
    ... 
 
    ... 
 
    d3.json("data.json", function(error, json) { 
 
       if (error){ 
 
       console.log(error); 
 
       } 
 
    ... 
 
    ... 
 
</script>

은 어떻게 D3에 내가합니다 (controller에서) API에서 수신 데이터를 전달할 수 있습니다 표시 (in 및 html 파일).

+0

을 컨트롤러에서 Ajax를 이미 수행 했으므로 d3.json을 수행 할 필요가 없으므로 d3.json 성공 블록 내에서 코드를 이동해야합니다. 그러면 약속의 기능으로 전환합니다. – Cyril

+0

@Cyril, 이제 감사합니다. 데이터에 액세스 할 수 있습니까? – dmx

답변

1

더 "각 방법은"서비스에 loadind 데이터이며, 지침을 만드는 것은처럼 D3 성분을 렌더링하기 위해 : 용도에

.service('dataLoader', function($http, $location, $stateParams){ 
    return { 
     get: function() { 
      var id = $stateParams.id;    
      return $http 
       .post('http://' + $location.host() + id, {id: id } , {}) 
       .then(function(d){ 
        return d.data; 
       }) 
       .catch(function(err){ 
        return err; 
       }); 
      } 
    } 
}) 

.directive('mapElement', function(){ 
    return { 
    restrict: 'E' 
    scope: {}, 
    controller: function(dataLoader) { 
     ... 
     var force = d3.layout.force().size([width, height]).on("tick", tick); 

     var svg = d3.select("#d3g").append("svg").attr("width", width).attr("height", height); 
     var link = svg.selectAll(".link"), 
      node = svg.selectAll(".node"); 
     ... 
     ... 
     dataLoader 
     .get() 
     .then(function(data){ 
      d3.json(data, function(error, json) { 
        if (error){ 
        console.log(error); 
        } 
       ... 
       ... 
      } 
     }) 
    } 
}); 

당신의 HTML에 넣어이 지시어 :

<map-element></map-element> 
관련 문제