我用AngularJS创建了一个简单的TODO应用程序。
我这里有一张待办事项的清单。我可以删除,设置为已完成,并添加新的。
我也可以通过双击粗体文本编辑标题。现在,将出现一个文本输入:
基本上,每一行(在ng-repeat下面)都有一个不可见的输入,我用它的可见性来处理它:
<li ng-repeat="todo in vm.todos....." ...>
<div ng-hide="vm.isTheEdited(todo)"> //this is "read" mode
....show checkbox + Label + Delete button
</div>
<input ... show="vm.isTheEdited(todo)".... /> // this is the "edit" mode
</li>
一切正常
但我在一个应用程序中看到了这个计算观察者的代码。
所以我增强了它以字符串的方式显示独特的项目。
(我所做的只是补充):
Array.prototype.unique = function(a){
return function(){ return this.filter(a) }
}(function(a,b,c){ return c.indexOf(a,b+1) < 0 })
console.log(getWatchers().unique().length);
console.log(getWatchers().unique().map(function (a){return a.exp;}));
)*
这不重要。
重要的是,它有许多重复的观察者!!!
看看结果:
问为什么我有这么多的重复条目,我怎样才能减少观看者的数量?(并消除DUP)
我所做的只是使用ng-show和hide通过函数的一些值。
事实上,我不认为有任何重复:ngShow和ngHide都创建了一个观察器,并且使用本机指令无法避免这种情况:在本例中,每一行至少应该有两个观察器。
删除观察器(所有观察器)的唯一方法是创建一个自定义指令,该指令:
示例:
module.directive('myClick', function() {
return {
link: function(scope, element) {
var span = element.find('span'),
input = element.find('input');
input.hide();
span.on('dblclick', function() {
if (span.is(':visible')) {
span.hide();
input.show();
input.val(span.text());
}
});
input.on('keypress', function(e) {
if (e.which === 13) {
input.hide();
span.show();
span.text(input.val());
}
});
}
}
});
HTML:
...
<div ng-repeat="todo in vm.todos" my-click>
<span>{{todo}}</span><input>
</div>
...