【发布时间】:2012-10-28 23:19:54
【问题描述】:
我一直在尝试定义指令,以便可以在表单中显示不同的“小部件”,具体取决于存储在数据库中的字段类型及其参数。我需要对不同类型的场景做出反应,因此需要指令来处理布局。
在玩几个例子的同时,我想出了一个 *kinda* 工作的代码:
HTML
<input type="text" ng-model="myModel" style="width: 90%"/>
<div class="zippy" zippy-title="myModel"></div>
指令
myApp.directive('zippy', function(){
return {
restrict: 'C',
// This HTML will replace the zippy directive.
transclude: true,
scope: { title:'=zippyTitle' },
template: '<input type="text" value="{{title}}"style="width: 90%"/>',
// The linking function will add behavior to the template
link: function(scope, element, attrs) {
// Title element
element.bind('blur keyup change', function() {
scope.$apply(read);
});
var input = element.children();
function read() {
scope.title = input.val();
}
}
}
});
这似乎可行(尽管明显比 *proper* angularJS 变量绑定慢),但我认为必须有更好的方法来做到这一点。谁能解释一下这个问题?
【问题讨论】:
-
只是好奇,我知道你最终不需要手动调用 $apply,但你为什么要同时绑定
blur和change?这不是多余的吗?如果没有,我很想知道与仅使用keyup blur有什么区别。 -
blur和change是不同的,但我相信出于实际目的,keyup和change在功能上是相似的。唯一的区别是,如果我以编程方式更改输入的值,使用change会触发一个事件(输入的数据更改),而将change留在外面会使这种更改不可见,除非它来自按键。请记住,这是“很久以前”的事了,我不知道我在用 angularJS 这个令人敬畏的野兽做什么;)
标签: javascript data-binding frameworks angularjs