AngularJS 指令和从服务中提取数据 [英] AngularJS directive and pulling data from a service
问题描述
我正在尝试找出将数据从服务中提取到我的指令中的正确方法.出于某种原因,加载数据时不会触发我的 $watch 语句.
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/
Simple JSFiddle http://jsfiddle.net/jamesamuir/m85Ka/1/
但是,我不确定我是否以正确的方式处理这个问题.我试图深入研究 Directives 的文档,但它似乎并没有提供太多解决这个问题的见解.
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 并保留了 $watch 虽然它不需要.
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.$apply
回调相关联.在这种情况下你不能return
,而是使用回调,因为数据将像这样异步加载:
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屋!