Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

javascript - Angular js - Highlight dom when value changes

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.

Here is a plunkr

http://plnkr.co/edit/xWk5UBwifbCF2raVvw81?p=preview

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.

Any help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

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);
        }
      });
    }
  };
}]);

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.

demo: http://jsbin.com/vutevifadi/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...