我尝试了,尝试了,尝试了。我做错了。我上了非常基础的课程CodeSchool,因为我对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语法时,一种常见的模式是创建一个变量以首先对控制器进行别名,以便能够从回调函数内部进行访问。为了清楚地说明发生了什么,我将此变量命名为与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/