【问题标题】:Angular custom directive not repainting when the datasource changes数据源更改时角度自定义指令不会重新绘制
【发布时间】:2016-07-06 17:10:56
【问题描述】:

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

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

坏人

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

该指令现在位于ng-repeats 通过数组的<li> 内部,我给它一个隔离范围,该范围了解数组项和该<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
  }
});

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

【问题讨论】:

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


    【解决方案1】:

    问题出在您的listLength 变量中。确实,您正在跟踪集合,但您没有更新 renderGradient 所依赖的 listLength

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

    修复:

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

    更新的 plunker here.

    【讨论】:

    • 是的,就是这样,谢谢!在将指令范围内的 origArray 添加回指令之前,我从 DOM 节点计算了 listLength,并且从未更新过该变量。
    猜你喜欢
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2014-01-18
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多