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
相关产品推荐
相关产品推荐

