Angularjs undefined err scope variable



嗨,伙计们,我在使用angularjs时遇到了一些困难。我今天花了一整天的时间试图弄清楚这一点!我是新手,真的很困,所以希望有人能帮忙。我收到错误"无法读取未定义的属性'长度'。.我的程序有一个从.json文件中获取的对象数组"$scope.products"。 我过滤此数组以仅显示那些具有类别:"特别优惠"..

$scope.specialOffers = $filter('filter')($scope.products,{category:"Special 
Offers"}, true);

然后获取这个新数组的长度并将其传递给我的 randomInt 函数,从而创建一个介于 0 和数组长度之间的随机整数.. 但由于某种原因,'$scope.specialOffers' 显示为未定义.. 这是完整的控制器代码:

app.controller('ProductsController', ['$scope','$filter', 'productFactory', 
'$location', '$routeParams', 
function ($scope, $filter, productFactory, $location, $routeParams) {
$scope.path;
$scope.category;
$scope.products;
$scope.rand;
$scope.specialOffers;
$scope.id = $routeParams.id;
specifyCategory();
getProducts();
$scope.specialOffers = $filter('filter')($scope.products,{category:"Special Offers"}, true);
$scope.rand = randomInt($scope.specialOffers.length, 0);
function specifyCategory() {
    $scope.path = $location.path();
    if ($scope.path == "/products/woodentoys") {
        $scope.category = "Wooden Toys"
    } else if ($scope.path == "/products/woodenaccessories") {
        $scope.category = "Wooden Accessories"
    } else if ($scope.path == "/products/specialoffers"){
        $scope.category = "Special Offers"
    }
}
function getProducts() {
    productFactory.getProducts()
        .then(function (response) {
            $scope.products = response.data;
        }, function (error) {
            $scope.status = 'unable to load product data ' + error.message;
        });
}
function randomInt(max,min){
    max++;
    return Math.floor((Math.random())*(max-min))+min;
}
}]);

这是我关于堆栈溢出的第一个问题,因此感谢您的耐心等待提前非常感谢!

在没有看到实际错误消息的情况下,我的第一个猜测是$scope.products在被过滤之前没有被设置。 看起来getProducts正在返回一个异步承诺:

function getProducts() {
    productFactory.getProducts()
        .then(function (response) {
           $scope.products = response.data;
        }, function (error) {
           $scope.status = 'unable to load product data ' + error.message;
    });
}

如果尚未尝试,请在匿名回调函数中移动对此数据的访问。

function getProducts() {
    productFactory.getProducts()
        .then(function (response) {
            $scope.products = response.data;
            $scope.specialOffers = $filter('filter')($scope.products, {category:"Special Offers"}, true);
            $scope.rand = randomInt($scope.specialOffers.length, 0);
        }, function (error) {
            $scope.status = 'unable to load product data ' + error.message;
        });
}

发生这种情况是因为您获取产品的请求需要一些时间,这意味着当您尝试访问 $scope.products 而请求尚未完成时,这会导致显示为未定义

尝试在请求的回调中应用过滤器或考虑使用 $watch

最新更新