AngularJS应用程序错误:变量附加到$ scope对象,但尚未定义

时间:2019-07-14 10:31:48

标签: angularjs scope

我正在使用Giphy.com api开发AjgularJS 1.6中的应用程序。

我已将giphyList变量附加到$ scope对象,但出现错误:Cannot read property 'length' of undefined

这是控制器中的代码:

app.controller("giphyCtrl", ["$scope", "$http", "$filter", "$timeout", function($scope, $http, $filter, $timeout) {
    var url = "https://api.giphy.com/v1/gifs/random?api_key=PTZrBlrq8h2KUsRMeBuExZ5nHyn7dzS0&tag=&rating=G";
    $scope.giphyList = [];
    $scope.search = "";
    $scope.filterList = function() {
        var oldList = $scope.giphyList || [];
        $scope.giphyList = $filter('filter')($scope.giphys, $scope.search);
        if (oldList.length != $scope.giphyList.length) {
            $scope.pageNum = 1;
            $scope.startAt = 0;
        };
        $scope.itemsCount = $scope.giphyList.length;
        $scope.pageMax = Math.ceil($scope.itemsCount / $scope.perPage);
    };

    $http.get(url)
        .then(function(data) {
            // giphy arary
            $scope.giphys = data.data.results;
            $scope.filterList();
            console.log(data);

            // Paginate
            $scope.pageNum = 1;
            $scope.perPage = 24;
            $scope.startAt = 0;
            $scope.filterList();

            $scope.prevPage = function() {
                if ($scope.pageNum > 1) {
                    $scope.pageNum = $scope.pageNum - 1;
                    $scope.startAt = ($scope.pageNum - 1) * $scope.perPage;
                }
            };

            $scope.nextPage = function() {
                if ($scope.pageNum < $scope.pageMax) {
                    $scope.pageNum = $scope.pageNum + 1;
                    $scope.startAt = ($scope.pageNum - 1) * $scope.perPage;
                }
            };

            $scope.selectedIndex = null;
            $scope.selectedContact = null;

            $scope.fetchSingleContct = function(contact, index) {
                $scope.selectedIndex = index;
                $scope.selectedContact = contact;
            }

        });    
}]);

请,您能帮我弄清楚我的错误在哪里吗?

1 个答案:

答案 0 :(得分:0)

 $filter('filter')($scope.giphys, $scope.search)- returns undefind.

在以下位置检查过滤条件以及从服务器返回的信息:

$scope.giphys = data.data.results;