Hi I spent the last two days trying to make a view depending upon the response of an async http service. But it doesn't work for me. Can any one help me out?
Here there is the code for the basic idea, but the original one is a bit different:
var myApp = angular.module('app', []);
myApp.directive('dashboard',['service1',function(service1){
return {
templateUrl: 'sometemplate.html',
controller: function ($scope) {
$scope.data = {};
service1.get('keyXXX');
$scope.$watch(service1.data['keyXXX'],function(n,o){
//how to make this work???
//I always get null or it would not get executed at all
});
}
}
}])
.service('service1',['someAsyncservice',function(someAsyncservice){
var _s={
data:{},
get:function(key){
if(this.data[key]==undefined)
{
this.data[key]={status:"loading",data:{}};
}
someAsyncservice().then(function(result){
_s[key].data=result;
_s[key].status="success";
});
}
}
return _s;
}])
update:
This is an extended example, using mostly your original code, showing how to completely go without
$apply
or$watch
. Simply by using$q
you can bypass most of the problems the first two functions could generate:previous answer:
Though there are probably other (better) ways, simply wrap your watched value in a function. E.g.:
But note, that this will only work if
someAsyncservice
actually triggers the digest cycle (e.g. by using$q
and similar)!