Angularjs undefined err范围变量

时间:2018-03-03 20:51:13

标签: javascript angularjs json angularjs-scope

大家好,我对angularjs有些困难。我今天整整都花了一整天努力解决这个问题!我是新手,并且真的陷入困境,希望有人可以提供帮助。我收到错误'无法读取属性'长度'未定义' ...我的程序有一系列对象&$; $ scope.products'取自.json文件..我过滤此数组只显示那些产品 类别:'特别优惠' ..

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

}]);

这是关于堆栈溢出的第一个问题,所以请耐心等待 非常感谢提前!

2 个答案:

答案 0 :(得分:1)

没有看到实际的错误消息,我的第一个猜测是$ 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;
        });
}

答案 1 :(得分:0)

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

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