Using angular-seed project: In directives.js
var names = [];
Animals.query(function(data){ // Animals.query() from service.js
console.log(data.Names); // output > [Object, Object..., Object]
names = data.Names; // attempt to bind to outer variable
});
console.log(names); // output > []
I can see the data there but I need it outside the function. How do I get it outside the function? console.log(names); happens before console.log(data.Names); I know it has to do with closures and maybe callbacks and I've tried many things and but I can't seem to get them to work for my case. I end up with an ever expanding mess of functions wrapped in callbacks wrapped in functions with still no binding to outside variable. I don't want to 'pollute the global namespace' but I need ahold of the data outside the inner function. The end-purpose is to get the data to be available for d3.js processing. There must be a simpler way. Can someone please help me with this particular case?
Hope I'm not misunderstanding you: you've already created (I assume) a function Animals as a service. Why don't you inject that in the controller of the directive's scope?
as in :
function Controller($scope, Animals){
$scope.names = [];
$scope.updateD3viz = function(){
// do your d3 stuff here
$scope.names = Animals.query(); // or whatever
}
}
$scope
will be accessible from the directive's link(scope,elem,attrs)
method.
I had to do something similar (angular and d3) and i ended up having a d3 graph as a controller's scope property to make sure it was included in angular's lifecycle.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.