Angularjs指令不获取数据

时间:2013-10-22 15:38:01

标签: angularjs angularjs-directive

我有服务从服务器获取数据并将其发送到控制器:

服务:

publicApp.angularModule.factory('resultService', function ($http) {
        return {
            getResult: function() {
                return $http.get("/Result/GetResult")
                    .success(function(result) {
                        return result.data;
                    }).error(function(result) {
                        console.log("error" + result);
                    });
            },
        };
    });

控制器:

publicApp.angularModule.controller('PublicResultCtrl', function ($scope, $location, resultService) {

    resultService.getResult().then(function (resultResponse) {
        $scope.data = resultResponse.data;
        $scope.graph = [];

        _.forEach($scope.data.TreningExerciseScores, function(item) {
            $scope.graph.push(addDataToGraph(item.Item2, item.Item1));
        });

    });

    var addDataToGraph = function (num, text) {
        return {
            y: num,
            legendText: text,
        };
    };

});

我有指令应该从控制器获取数据。我这样称呼指令:

<div id="graph" style="width: 200px; height: 200px" canvasjs graphData="graph"></div> 

这是我的指示:

publicApp.angularModule.directive('canvasjs', function () {


    return {
        restrict: 'A',
        scope: {data : '=graphData'} ,
        link: function (scope, element, attrs) {

            scope.$watch('data', function (data) {
                    console.log(scope.data);

            });         
        }
    };
});

但是scope.data是未定义的。我知道$ http.get是异步操作,但不应该是范围。$ watch获取更新?

3 个答案:

答案 0 :(得分:2)

如果您要在控制器中处理承诺:

resultService.getResult().then(function (resultResponse) {
        $scope.data = resultResponse.data;
        $scope.graph = [];

        _.forEach($scope.data.TreningExerciseScores, function(item) {
            $scope.graph.push(addDataToGraph(item.Item2, item.Item1));
        });

    });

您无需在服务中处理它:

getResult: function() {
                return $http.get("/Result/GetResult");
            },

如果您只想处理服务中的错误,那么您需要再次包装一个promise。您可以使用$q.when

getResult: function() {
                return $http.get("/Result/GetResult")
                    .success(function(result) {
                        return $q.when(result.data);
                    }).error(function(result) {
                        // not sure what you want to do here
                        console.log("error" + result);
                        return $q.when(result);

                    });
            },

$q.when将围绕对象包装一个承诺,如果它还不是一个承诺。

答案 1 :(得分:2)

尝试将值传递给指令:canvasjs="graph"

在我的例子中,我模拟来自服务的响应并返回承诺。

<强> HTML

<div ng-controller="fessCntrl">
    <div id="graph" style="width: 200px; height: 200px" canvasjs="graph"></div>
    <pre>   graph:  {{graph|json}}  </pre>
    <pre>   data:  {{data|json}}  </pre>  
</div>

<强> JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function ($scope, resultService) {

    resultService.getResult().then(function (resultResponse) {
        console.log(resultResponse);

        $scope.data = resultResponse.data;
        $scope.graph = [];

        angular.forEach($scope.data.TreningExerciseScores, function (item, key) {
            $scope.graph.push(addDataToGraph(item.Item2, item.Item1));
        });


    });

    var addDataToGraph = function (num, text) {
        return {
            y: num,
            legendText: text,
        };
    };

});

fessmodule.$inject = ['$scope', 'Data'];

fessmodule.directive('canvasjs', function () {
    return {
        restrict: 'A',

        link: function (scope, element, attrs) {

            scope.$watch('data', function (data) {
                console.log("fff", scope.data);

            });
        }
    };
});

fessmodule.factory('resultService', ['$resource', '$q', function ($resource, $q) {
    var input = {
        data: {
            TreningExerciseScores: [{
                Item1: "aaa"
            },
            {
                Item2: "bbb"
            }]
        }
    };

    var factory = {
        getResult: function (selectedSubject) {
            var deferred = $q.defer();

            deferred.resolve(input);

            return deferred.promise;
        }

    }
    return factory;
}]);

演示 Fiddle

答案 2 :(得分:0)

您无法在success()处理程序中返回数据,并希望它能够将其恢复。您必须链接另一个承诺(返回defer.promise()),或在控制器中执行success并修改结果中的$ scope。或者只返回已经是承诺的整个$http电话。