You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS报错ReferenceError: categories is not defined的原因是什么?

问题原因

  • $http.get 是异步网络请求,你写在回调外的 $scope.specials 赋值逻辑会先于请求响应执行,此时 $scope.categories 还未被赋值。
  • 你代码中直接使用 categories[0] 读取数据,当前作用域下不存在名为 categories 的独立变量,你定义的是挂载在 $scope 下的 $scope.categories,直接读取 categories 自然会抛出未定义错误。

解决方案

把 $scope.specials 的赋值逻辑移动到请求成功的回调函数内,等接口返回数据后再执行相关操作即可,修改后的控制器代码如下:

(function(){

    app.controller('productsCtrl', ['$scope','$cookies', '$http', function($scope,$cookies,$http){

        $http.get("controllers/data.json").then(function (response) {
            $scope.categories = response.data;
            // 拿到接口返回数据后再处理specials
            $scope.specials = [$scope.categories[0].laptops[1], $scope.categories[1].accessories[0]];
        }); 

    }]);

})(); 

内容的提问来源于stack exchange,提问作者M Dube

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 19:06:00