此链接有一个d3树形图代码 -
http://jsfiddle.net/cyril123/h0q6xb45/1/
现在这里的数据是静态的,即它在控制器的范围内,但不是从任何地方加载的。所以我编写了一个服务 -
app.service('grabdata', function($http){
var data = [];
$http.get('someApi').then(function success(response){
var company = [];
var wtdCagr = [];
var children = [];
for(var i=0;i<response.data.length;i++){
company.push(response.data[i].companies);
wtdCagr.push(response.data[i].wtdcagr);
children.push({name:response.data[i].companies, value: 3241});
}
data.push({name:"flare", children:children});
});
return {
getData: function(){
return data[0];
}
};
});
我设置了控制器 -
app.controller('myController', ['$scope', '$http','grabdata', function($scope, $http, grabdata) {
$scope.$watch(grabdata.getData, function(change){
$scope.data = change;
}, true);
}]);
我编辑了指令 -
return {
restrict: 'EA',
scope: {data: '='},
link: function(scope, elem, attrs) {
scope.$watch(scope.data, function(newValue){
console.log(newValue);
var root = scope.data;
});
var root = scope.data;
但是我在我的控制台上出现了这个错误 -
TypeError: Cannot read property 'length' of undefined
这意味着数据不在指令中,我做错了什么?
答案 0 :(得分:0)
好的,让我为你重写一些事情,这样你可以尝试让我知道它是否正常:
//service
app.service('grabdata', function($http, $q){
var data = [];
return({
getData:getData
});
function getData(){
var defer = $q.defer();
$http.get('someApi').then(function success(response){
var company = [];
var wtdCagr = [];
var children = [];
for(var i=0;i<response.data.length;i++){
company.push(response.data[i].companies);
wtdCagr.push(response.data[i].wtdcagr);
children.push({name:response.data[i].companies, value: 3241});
}
data.push({name:"flare", children:children});
defer.resolve(data[0]);
return defer.promise;
}
});
//controller
app.controller('myController', ['$scope', '$http','grabdata', function($scope, $http, grabdata) {
var $scope.data = [];
grabdata.getData().then(function(response){
$scope.data = response;
});
$scope.$watch($scope.data, function(newData,oldData){
if(newData !== oldData){//workout some logic since this is array or object ??
$scope.data = newData;
}
}, true);
}]);
$ http服务调用是异步的,您需要向对数据感兴趣的一方返回承诺,并且当承诺得到解决后,您将获得您的数据。我没有说明为什么你的对象长度未定义,只要确保response.data
存在。我建议阅读有关异步数据处理的内容,您的生活会更轻松。您也可以返回$ http.get(&#39; / someapi&#39;)并在控制器中处理数据,如果这样你想要的话