AngularJS directive and pulling data from a service

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-15 15:32:23

问题


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);
                }
            });


        }

Simple 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.


回答1:


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.

The problem is here:

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");
        });
}

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;
});

Instead of:

$scope.loadtext = testService.getJSON();

http://jsfiddle.net/m85Ka/10/




回答2:


While Tim Withers suggestion will work for your problem, the correct way to load data is either from the view's controller function or in the directive's own controller.



来源:https://stackoverflow.com/questions/16590120/angularjs-directive-and-pulling-data-from-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!