Angular ReferenceError:未定义响应

时间:2016-04-09 22:42:52

标签: javascript angularjs

我是Angular的新手,我正在做一些测试,并在本教程中遇到困难: angular.min.js:116 ReferenceError:响应不在onUserComplete

    var app = angular.module('example', []);
    var mainController = function($scope, $http){

        var onUserComplete = function($scope){
            $scope.user = response.data;
        }

        var onError= function(reason){
            $scope.error = "Could not fetch data";
        }

        $scope.search = function(username){
            $http.get("https://api.github.com/users/"+username)
            .then(onUserComplete, onError);
            $scope.username = "angular";
            $scope.message = "Hello World"
        }
    }
    app.controller('mainController', mainController);

谢谢!!!

2 个答案:

答案 0 :(得分:1)

这里没有将$ scope作为参数发送到函数中的意思,尽量避免在教程之后这样做

我认为教程要求您在此处将$scope更改为response

var onUserComplete = function(response){
    $scope.user = response.data;
}

在这里,您要将回复的数据分配到scope.user,您可以在$scope gp

的任何位置使用它

答案 1 :(得分:0)

当您仔细查看时,您的函数onUserComplete()正在使用response变量,但无论如何都没有收到此变量。你需要传递它。

正如Daniel所提出的,更正是将函数参数更改为response(这是函数将从$http对象接收的内容。

    var app = angular.module('example', []);
    var mainController = function($scope, $http){

        var onUserComplete = function(response){
            $scope.user = response.data;
        }

        var onError= function(reason){
            $scope.error = "Could not fetch data";
        }

        $scope.search = function(username){
            $http.get("https://api.github.com/users/"+username)
            .then(onUserComplete, onError);
            $scope.username = "angular";
            $scope.message = "Hello World"
        }
    }
    app.controller('mainController', mainController);