AngularJS ng风格的跑步两次
AngularJS ng-style running twice?
我的randomWidth()函数调用两次时遇到问题,即使我从元素中删除ng repeat属性,它仍然调用两次。我似乎不知道如何绕过这个问题。我想有办法解决这个问题,或者可能是我明显遗漏了什么?
HTML:
<div id="body-wrapper" ng-app="gallery" ng-controller="mainCtrl">
<section id="sidebar">
<h1>Gallery</h1>
</section>
<main>
<div class="box" ng-repeat="img in imgs" ng-style="{'width': randomWidth()}">
<div class="box-wrapper"></div>
</div>
</main>
</div>
Javascript:
angular.module('gallery', [])
.controller('mainCtrl', function($scope){
$scope.imgs = [
{
title: 'image1'
},
{
title: 'image2'
},
{
title: 'image3'
},
{
title: 'image4'
},
{
title: 'image5'
},
{
title: 'image6'
}
];
$scope.randomWidth = function(){
const widths = ['25%', '33%', '40%', '50%'];
const max = widths.length;
const min = 0;
var r = Math.floor(Math.random() * (max - min)) + min;
console.log(widths[r]);
return widths[r];
}
})
实时代码:http://codepen.io/daviddiefenderfer/pen/qZpqdK
查看此更新的代码笔-您需要在JS中调用randomWidth,每个图像调用一次。按照你的设置方式,它被称为第一次,这最终会修改你的元素,触发一个摘要循环,触发另一个对randomWidth的调用,等等,直到Angular停止你,因为它检测到了无限循环。
http://codepen.io/lwalden/pen/KzZWXK
更改为HTML:
<div class="box" ng-repeat="img in imgs" ng-style="{'width': img.style}">
更改为JS:
angular.module('gallery', [])
.controller('mainCtrl', function($scope){
$scope.randomWidth = function(){
const widths = ['25%', '33%', '40%', '50%'];
const max = widths.length;
const min = 0;
var r = Math.floor(Math.random() * (max - min)) + min;
console.log(widths[r]);
return widths[r];
}
$scope.imgs = [
{
title: 'image1',
style: $scope.randomWidth()
},
{
title: 'image2',
style: $scope.randomWidth()
},
{
title: 'image3',
style: $scope.randomWidth()
},
{
title: 'image4',
style: $scope.randomWidth()
},
{
title: 'image5',
style: $scope.randomWidth()
},
{
title: 'image6',
style: $scope.randomWidth()
}
];
})
我认为这个问题已经得到了充分的回答。
我建议看一下这篇关于$digest
的文章。
Note: At a minimum, $digest will run twice even if your listener functions don’t change any models. As discussed above, it runs once more to make sure the models are stable and there are no changes.
相关文章:
- ng在一页中包含两次相同的部分页面
- ng单击需要两次才能更新视图
- AngularJS ng风格的跑步两次
- Angular JS:使用ng重复计算每行两次之间的差
- ng标记输入,不允许在文本框中输入两次相同的文本
- 新指令导致NG改变两次触发
- ng 类指令调用执行两次
- ng-重复运行两次(角度)
- 递归自定义树视图 angularjs 指令调用 ng 单击两次
- 控制器函数使用 ng-show 调用两次
- 不能在ng类上重复两次相同的条件
- AngularJS在一个表中使用ng重复两次
- 在Angular的dom元素上使用两次ng-controller
- Mobilefirst Ionic ng启动应用程序点击两次
- 为什么使用ng-model两次输入字段工作?
- 所有的ng-click事件都触发两次
- 如何从两次或三次嵌套的ng-repeat作用域访问控制器的作用域
- Angular指令编译器触发了两次ng-click
- $scope's方法通过ng-click调用:由IE执行两次
- Angular JS控制器被调用两次(ng-controller)