Angular js - 值更改时突出显示 dom [英] Angular js - Highlight dom when value changes
问题描述
这里有角菜鸟.我想知道当范围中的值以某种方式发生变化时,更改 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
http://plnkr.co/edit/xWk5UBwifbCF2raVvw81?p=preview
基本上,当数据通过单击上面 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.
有什么帮助吗?
推荐答案
我认为最好观察每个 highlighter 的具体值,而不是观看整个集合.例如:
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>
这样,highlighter
指令可以非常简单,例如:
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);
}
});
}
};
}]);
尽管如此,要使此功能起作用,您必须告诉 angular 数据实际上已更改.目前情况并非如此,因为角度跟踪people
对象身份.覆盖它的那一刻,angular 将删除所有关联的 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"
这将告诉 angular 将数组的索引视为身份.
which will tell angular to treat the index of the array as identity.
演示:http://jsbin.com/vutevifadi/1/
这篇关于Angular js - 值更改时突出显示 dom的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!