2016-11-27 2 views
0

in meiner Anwendung Controller ich eine Anfrage an meine API. Es sieht wie folgt aus:Wie json von angularjs zu d3 übergeben?

.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); 
     }); 
     }, 
    }) 

mein d3 Skript ist so etwas wie dieses:

<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>

Wie kann ich passieren Daten, die ich von api erhalten (im controller) meiner d3 Anzeige (in und HTML-Datei).

+0

Nun, du musst d3.json nicht machen, da du bereits den Ajax im Controller gemacht hast, also musst du den Code innerhalb des d3.json Erfolgsblocks in die then Funktion des Versprechens verschieben. – Cyril

+0

@Cyril danke, jetzt wie ich habe Zugang zu Daten? – dmx

Antwort

1

Mehr "Winkel way" sind loadind Daten in einer Service und eine Richtlinie zu schaffen, wie Ihre d3 Komponente zu machen:

.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); 
        } 
       ... 
       ... 
      } 
     }) 
    } 
}); 

diese Richtlinie Verbrauch, nur in Ihrem HTML setzen:

<map-element></map-element> 
Verwandte Themen