gpt4 book ai didi

javascript - 迭代 JSON 时 NG-repeat 不起作用

转载 作者:行者123 更新时间:2023-12-03 08:53:31 25 4
gpt4 key购买 nike

我已经尝试过,尝试过,尝试过。我无法做到这一点。我参加了 CodeSchool 的一门非常基础的类(class),因为我对 Angular 非常感兴趣。虽然我无法让这个该死的重复工作。 -- 非常感谢您的帮助!

<小时/>
    'use strict';
var myApp = angular.module('myApp', [])

.controller('MatchListCtrl', ['$scope', '$http', function ($scope, $http) {
console.log('Attempting API Call');

$scope.matches = [];

$http.get("matches.json")
.success(function (response) {
console.log('Grabbed matches.json successfully!');
//Loop through each item and put it onto the matches var
angular.forEach(response, function (item) {
$scope.matches.push(item);
});

console.log('Total of ' + $scope.matches.length + ' matches in the array.');
})

$scope.theMatches = function ($scope) {
return $scope.matches;
}

}]
);
<小时/>

这是我的 HTML:

<div ng-controller="MatchListCtrl as matchCtrl">
<p style="font-weight:bold;">{{matchCtrl.getMatches().length}} - Items in the array.</p>
<ul>
<li ng-repeat="x in matchCtrl.theMatches">{{x.when}}</li>
</ul>

最佳答案

我已经获取了您的代码片段并对其进行了修改,以将其完全更改为 ControllerAs 语法。您最初的代码是混合样式,并且有一些可以删除的冗余。

使用 ControllerAs 语法时,常见的模式是首先创建一个变量作为 Controller 的别名,以便能够从内部回调函数进行访问。为了非常清楚地表明这里发生了什么,我将此变量命名为与 HTML 中的别名相同的名称。

另请注意,此处完全删除了对 $scope 的引用,以及冗余函数 theMatches

var myApp = angular.module('myApp', [])

.controller('MatchListCtrl', ['$http',
function($http) {

var matchCtrl = this; //consistent reference to controller object

console.log('Attempting API Call');

matchCtrl.matches = [];

$http.get("matches.json")
.success(function(response) {
console.log('Grabbed matches.json successfully!');
angular.forEach(response, function(item) {
matchCtrl.matches.push(item);
});

console.log('Total of ' + matchCtrl.matches.length + ' matches in the array.');
})
}
]);
<div ng-controller="MatchListCtrl as matchCtrl">
<p style="font-weight:bold;">{{matchCtrl.matches.length}} - Items in the array.</p>
<ul>
<li ng-repeat="x in matchCtrl.matches">{{x.when}}</li>
</ul>
</div>

关于javascript - 迭代 JSON 时 NG-repeat 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32597388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com