角JS - 高亮DOM当值发生变化 [英] Angular js - Highlight dom when value changes

查看:134
本文介绍了角JS - 高亮DOM当值发生变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面角noobie。
我想知道什么是改变DOM时,在范围内的值通过某种方式改变的最佳途径。我读了它的不好把DOM操作逻辑控制器和多数民众指令的工作。

Angular noobie here. I would like to know what is the best way to change the dom when a value in the scope changes by some means. I read that its not good to put the dom manipulation logic in the controller and thats the job of directives.

下面是一个plunkr

Here is a plunkr

<一个href=\"http://plnkr.co/edit/xWk5UBwifbCF2raVvw81?p=$p$pview\">http://plnkr.co/edit/xWk5UBwifbCF2raVvw81?p=$p$pview

基本上当通过单击上面的plunkr加载数据按钮数据的变化,我想他们的价值观改变了细胞自动突出显示。我不能让它为我的生活工作。

Basically when the data changes by clicking the load data button in the plunkr above, i want the cells whose values changed to highlight automatically. I cant get it to work for the life of me.

任何帮助吗?

推荐答案

我认为这将是更好地观察每荧光笔的而不是看整个集合具体的值。例如:

I think it would be better to observer a concrete value per highlighter instead of watching the whole collection. E.g.:

<td highlighter="person.firstName">{{ person.firstName }}</td>

这样,荧光笔 -directive可以很简单,比如:

This way, the highlighter-directive could be very simple, like:

app.directive('highlighter', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
    scope: {
      model: '=highlighter'
    },
    link: function(scope, element) {
      scope.$watch('model', function (nv, ov) {
        if (nv !== ov) {
          // apply class
          element.addClass('highlight');

          // auto remove after some delay
          $timeout(function () {
            element.removeClass('highlight');
          }, 1000);
        }
      });
    }
  };
}]);

虽然,对于这个工作,你得告诉角度,该数据实际上改变。目前,这是并非如此,因为角度的轨道按对象的身份。你覆盖它的那一刻,角将删除所有相关的DOM元素。为了适应这一点,使用:

Though, for this to work you'll have to tell angular that the data actually changed. Currently this is not the case as angular tracks people by object-identity. The moment you overwrite it, angular will remove all associated dom-elements. To accomodate for this, use:

ng-repeat="person in people track by $index"

这将告诉角度来对待数组作为身份的索引。

which will tell angular to treat the index of the array as identity.

演示: http://jsbin.com/vutevifadi/1/

这篇关于角JS - 高亮DOM当值发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆