ng-repeat无法正常工作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ng-repeat无法正常工作相关的知识,希望对你有一定的参考价值。
我想使用ng-repeat
但它不起作用:
<!DOCTYPE html>
<html lang="en" ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular-route.js"></script>
</head>
<body ng-init="jj=[1,2,2,3]">
<ul>
<li ng-repeat="x in jj">{{x}}</li>
</ul>
</body>
</html>
输出屏幕为空白。输出源(取自浏览器的inspect元素):
<html class="ng-scope" lang="en" ng-app=""><head><style type="text/css">@charset "UTF-8";[ng:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular-route.js"></script>
</head>
<body ng-init="jj=[1,2,2,3]">
<ul>
<!-- ngRepeat: x in jj -->
</ul>
<!-- Code injected by live-server -->
<script type="text/javascript">
// <![CDATA[ <-- For SVG support
if ('WebSocket' in window) {
(function() {
function refreshCSS() {
var sheets = [].slice.call(document.getElementsByTagName("link"));
var head = document.getElementsByTagName("head")[0];
for (var i = 0; i < sheets.length; ++i) {
var elem = sheets[i];
head.removeChild(elem);
var rel = elem.rel;
if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") {
var url = elem.href.replace(/(&|?)_cacheOverride=d+/, '');
elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date().valueOf());
}
head.appendChild(elem);
}
}
var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://';
var address = protocol + window.location.host + window.location.pathname + '/ws';
var socket = new WebSocket(address);
socket.onmessage = function(msg) {
if (msg.data == 'reload') window.location.reload();
else if (msg.data == 'refreshcss') refreshCSS();
};
console.log('Live reload enabled.');
})();
}
// ]]>
</script>
</body></html>
答案
你有duplicates in your array,尝试using track by
像:
ng-repeat="x in jj track by $index"
工作范例:
<!DOCTYPE html>
<html lang="en" ng-app>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular-route.js"></script>
</head>
<body ng-init="jj=[1,2,2,3]">
<ul>
<li ng-repeat="x in jj track by $index">{{x}}</li>
</ul>
</body>
</html>
另一答案
问题是你在数组中有重复的元素
<ul>
<li ng-repeat="x in jj track by $index">{{x}}</li>
</ul>
您可以通过以下网址阅读有关track的更多信息
以上是关于ng-repeat无法正常工作的主要内容,如果未能解决你的问题,请参考以下文章
带有复选框和自定义适配器的 ListView,片段无法正常工作