AngularJS指令和拉动数据服务 [英] AngularJS directive and pulling data from a service
问题描述
我试图找出拉数据从一个服务我的指令的正确方法。出于某种原因,在加载数据时不会触发了我的手表$发言。
I am trying to figure out the correct way to pull data into my directive from a service. For some reason my $watch statement isn't triggered when the data is loaded.
link: function(scope, element, attrs){
scope.loadtext = testService.getJSON();
scope.$watch(scope.loadtext, function(newValue, oldValue){
if (newValue !== oldValue){
alert("watch working");
element.addClass("red");
element.html(newValue.ok);
}
});
}
简单的jsfiddle http://jsfiddle.net/jamesamuir/m85Ka/1/
不过,我不知道如果我处理这个正确的方式。我试图挖成指令的文件,但它似乎并没有被提供迫切洞察解决这个。
However, I am not sure if I am approaching this the right way. I have tried to dig into the documentation for Directives but it doesn't seem to be providing much insight into solving this.
推荐答案
我不知道你的最终目标是什么,但我想你没有使用正确的方法。
无论如何,我更新了的jsfiddle,不停的$手表,虽然它不是必要的。
I'm not sure what your final goal is but I think you're not using the right approach. Anyway I updated the jsfiddle and kept the $watch though it's not needed.
问题是在这里:
this.getJSON = function() {
$http.get('http://ricardohbin.com/cors/testcors.php')
.success(function(data) {
$rootScope.$apply(function(){
alert(data);
return data;
});
}).
error(function(data, status, headers, config) {
alert(status + " | bad");
});
}
您返回数据
没有关联到的getJSON
但是到了 $ rootScope。$在这code适用
回调。你不能收益
在这种情况下,而不是使用回调的数据将异步那样被加载:
Your return data
is not associated to getJSON
but to the $rootScope.$apply
callback in this code. You cannot return
in this situation, instead use a callback as the data will be loaded asynchronously like that:
testService.getJSON(function(data) {
scope.loadtext = data;
});
而不是:
$scope.loadtext = testService.getJSON();
这篇关于AngularJS指令和拉动数据服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!