AngularJS 自定义指令双向绑定 [英] AngularJS Custom Directive Two Way Binding
问题描述
如果我有一个没有模板的 AngularJS 指令,并且我希望它在当前范围内设置一个属性,那么最好的方法是什么?
If I have an AngularJS directive without a template and I want it to set a property on the current scope, what is the best way to do it?
例如,一个计算按钮点击次数的指令:
For example, a directive that counts button clicks:
<button twoway="counter">Click Me</button>
<p>Click Count: {{ counter }}</p>
使用将点击计数分配给双向属性中的表达式的指令:
With a directive that assigns the click count to the expression in the two way attribute:
.directive('twoway', [
'$parse',
function($parse) {
return {
scope: false,
link: function(scope, elem, attrs) {
elem.on('click', function() {
var current = scope.$eval(attrs.twoway) || 0;
$parse(attrs.twoway).assign(scope, ++current);
scope.$apply();
});
}
};
}
])
有没有更好的方法来做到这一点?从我读过的内容来看,一个孤立的范围会过大,但我需要一个子范围吗?除了使用 $parse
之外,是否有一种更简洁的方法来写回指令属性中定义的范围变量.我只是觉得我让这件事太难了.
Is there a better way to do this? From what I've read, an isolated scope would be overkill, but do I need a child scope? And is there a cleaner way to write back to a scope variable defined in the directive attribute other than using $parse
. I just feel like I'm making this too difficult.
Full Plunker 此处.
Full Plunker here.
推荐答案
为什么隔离作用域是矫枉过正?它对这种事情非常有用:
Why is an isolate scope overkill? its pretty useful for exactly this kind of thing:
scope: {
"twoway": "=" // two way binding
},
对于这个问题,这是一个非常惯用的角度解决方案,所以这就是我要坚持的.
This is a pretty idiomatic angular solution to this problem, so this is what I'd stick with.
这篇关于AngularJS 自定义指令双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!