Angular自定义指令在数据源更改时不重新绘制

时间:2016-03-20 03:30:27

标签: angularjs angularjs-directive angularjs-ng-repeat

我正在处理angular(1.4.8)中的自定义指令,以在具有渐变背景颜色的垂直列表中显示项目数组。 I have put together a plunker to demonstrate。该指令采用初始RGB值(r,g和b的单独值),转换为HSL,然后降低阵列中每个附加索引的HSL饱和度值。

该指令适用于静态项目列表...

...但是在我的用例中,项目将由用户添加到数组中,并且该指令应考虑对数组的更改并重新呈现列表,并相应地调整颜色渐变。目前,我正处理如何让这部分工作的心理障碍。

该指令现在位于<li> ng-repeat通过数组的内部,我已经给它一个隔离范围,它知道数组项和该项中的项的索引。 <li>元素。我也将整个数组作为一个范围项传递给我,以便我可以$watch对它进行更改,感觉很乱并且无法正常工作:

return {
  ...
  scope: {
    origArray: '=',
    item: '=',
    idx: '@'
  },...
}

scope.$watchCollection(function() { return scope.origArray; }, function(newVal) {
  if (newVal) {
    console.log('there was a new item added');
    removeGradient(); // function to set element background to grey
    renderGradient(); // function to set element background to index-appropriate gradient color
  }
});

如果您对如何实现动态重新渲染有任何想法,我真的很感激。谢谢!

1 个答案:

答案 0 :(得分:1)

问题出在您的listLength变量中。您跟踪收藏集的确如此,但您没有更新listLength依赖的renderGradient

所以修复很简单,但首先,不需要通过查询dom来计算列表的长度。您只需执行listLength = scope.origArray.length

修复:

// In function decrementHsl, the first line: update listLength
listLength = scope.origArray.length;
...

更新的plunker here