Angular JS:完成对特定数字的 ng-repeat
Angular JS: completing an ng-repeat to a specific number
我正在尝试创建以下 UI 功能:
用户必须 select 三张图片。 ng-repeat 显示图像 selected,同时为剩余的 selection 留下空白图像。我能够使其工作如下:
<div class="tap" ng-repeat="point in points">
</div>
<div class="tap empty" ng-repeat="point in emptyPoints()">
?
</div>
其中 emptyPoints 是通过动态创建数组来计算的:
$scope.emptyPoints = function () {
var arr = [];
for (var cnt = 0; cnt < 3 - $scope.points.length; cnt++) {
arr.push({});
};
return arr;
};
视觉上这似乎有效,但在控制台上我收到一个错误:
Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations:
知道为什么吗?
有关您的错误的解释,您可以阅读关于 SO 的下一个答案:。引用同一个答案:
Angular expressions are evaluated at least two times per each $digest and $digest can run 10 times at a time (when bindings need to be "refreshed"). This means that expressions will be re-evaluated many times over. This is one of the common pitfall with Angular. So you need to make sure you don't call functions directly in your expressions. Instead, have the function executed once, inside the controller, and than use the function result in the expression.
对于您的特定情况,您可以使用固定长度 (3) 且在初始化时为空的单个数组,然后当用户 select 一个图像时,您将该图像推送到阵列上。
相反,您可以这样做
<div ng-class="point.selected ? tap : tap empty" ng-repeat="point in points">
<img ng-click="tapped(this)">
</div>
用户点击图像的任何地方
$scope.tapped = function(obj) {
obj.point.selected = true;
}
我正在尝试创建以下 UI 功能:
用户必须 select 三张图片。 ng-repeat 显示图像 selected,同时为剩余的 selection 留下空白图像。我能够使其工作如下:
<div class="tap" ng-repeat="point in points">
</div>
<div class="tap empty" ng-repeat="point in emptyPoints()">
?
</div>
其中 emptyPoints 是通过动态创建数组来计算的:
$scope.emptyPoints = function () {
var arr = [];
for (var cnt = 0; cnt < 3 - $scope.points.length; cnt++) {
arr.push({});
};
return arr;
};
视觉上这似乎有效,但在控制台上我收到一个错误:
Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations:
知道为什么吗?
有关您的错误的解释,您可以阅读关于 SO 的下一个答案:。引用同一个答案:
Angular expressions are evaluated at least two times per each $digest and $digest can run 10 times at a time (when bindings need to be "refreshed"). This means that expressions will be re-evaluated many times over. This is one of the common pitfall with Angular. So you need to make sure you don't call functions directly in your expressions. Instead, have the function executed once, inside the controller, and than use the function result in the expression.
对于您的特定情况,您可以使用固定长度 (3) 且在初始化时为空的单个数组,然后当用户 select 一个图像时,您将该图像推送到阵列上。
相反,您可以这样做
<div ng-class="point.selected ? tap : tap empty" ng-repeat="point in points">
<img ng-click="tapped(this)">
</div>
用户点击图像的任何地方
$scope.tapped = function(obj) {
obj.point.selected = true;
}