我被困住了。不知怎的,我无法让这个工作。我尝试从(仍然是本地的)JSON 文件加载 Web 应用程序的数据。此 JSON 的一部分包含颜色,如下所示:
{
"colors" : {
"1" : "yellow",
"2" : "green",
"3" : "red"
},
"stuff : {...}
}
我有一个非常基本的 HTML 文件,其中包含一些 header 内容。脚本加载在 header 中。有趣的部分如下所示:
<ul ng-controller="ColorController">
<li ng-repeat="(key,value) in colors" value="{{key}}">
{{key}}: {{value}}
</li>
</ul>
对应的Javascript:
var colors = {
"1": "lyellow",
"2": "lgreen",
"3": "lred"
};
var app = angular.module('test', []);
app.controller('ColorController', function($scope){
$scope.colors = colors;
$.getJSON('data.json')
.then(function(res){
$scope.colors = res.colors;
});
})
我首先尝试使用本地版本的颜色,因此变量颜色。效果很好并产生了所需的输出。我尝试切换到本地存储的 JSON。 console.log 显示了正确的解析。在调试控制台上,colors 和 res.colors 看起来相同。但页面上的列表并未更新。
我猜这与时间有关,但我不确定。有人能指出我正确的方向吗?
最佳答案
jQuery 的 getJSON
是在 Angular 的摘要循环之外执行的,因此 View 不会在 ajax 调用的 then then
中更新。如果您要在 $scope 变量赋值后添加一行 $scope.$apply()
, View 将会更新(请参阅 plunker: https://plnkr.co/edit/HLSYl0pI2AZ15qf5T5WM?p=preview )
不过,我建议使用 Angular 的 native $http.get
来获取 JSON。例如,请参阅此处的 plunker:https://plnkr.co/edit/F7e5ECYbl91mYhF3g848?p=preview
angular.module('test', [])
.controller('testCtrl', function($scope, $http) {
$http.get('colors.json')
.then(function(response) {
$scope.colors = response.data['colors']
})
})
关于javascript - getJSON 和 Angular 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41549149/