繁体   English   中英

angularjs-动态函数返回

[英]angularjs - dynamic function return

index.html

<div ng-repeat="object in objects" ng-style="getStyle(object.id)"></div>

controller.js

[...]

$scope.startWidth = 100;

$scope.getObject = [...]

$scope.getStyle = function(id) {
   var widthVal = $scope.startWidth;
   $scope.StartWidth += $scope.getObject(id).value;
   return { width : widthVal }
}

[...]

此代码遇到无限的$ digest循环。 我想我知道为什么。 返回值不应是动态的。 但是我怎么能意识到没有循环呢? 我想显示不同宽度的对象。 对象的宽度取决于前一个对象的值。

问题在于ng-style在每个子范围上都放置了一个$watchExpression

$watchExpression必须是幂等的 ,这意味着它必须通过多次检查返回相同的值。
如果$watchExpression 仍然很脏,则会触发另一个$digest

更新

在看到GRaAL好的答案后,我想出了一个更好的解决方案:

这是一个演示插件: http ://plnkr.co/edit/oPrTiwTOyCR3khs2iVga?p=preview

控制器:

$scope.$watchCollection('objects', function calculateWidths() {
  var tempWidth = 0;
  for( var i = 0; i < $scope.objects.length; i++) {
    tempWidth += $scope.objects[i].value;
    $scope.objects[i].width = tempWidth + 'px';
  }
});

标记:

<div ng-repeat="object in objects" ng-style="{width: object.width}">

旧解决方案

这是一个小矮人: http ://plnkr.co/edit/CqxOmV5lpZSLKxqT4yqo?p=preview

我同意Ilan的问题描述和解决方案-它可以在objects数组不改变的情况下起作用,否则宽度将被错误地计算。 如果可以在运行时添加/删除新对象,则最好在更改集合时(参见作用域的$watchCollection方法)或在每个摘要周期(对于元素的简短列表,应足够快)重新计算宽度。像那样:

  var widths = [];
  $scope.$watch(function calculateWidths() {
    var tempWidth = 0;
    widths = [];
    angular.forEach($scope.objects, function(obj) {
      tempWidth += obj.value;
      widths.push(tempWidth);
    });
  });

  $scope.getStyle = function(idx){
    return {width: widths[idx] + 'px'}
  }

这是the子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM