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>
通过该点击数分配给在双向属性除权pression一个指令:
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();
});
}
};
}
])
有没有更好的方法来做到这一点?从我读过,一个孤立的范围将是矫枉过正,但我需要孩子的范围?并有写回的指令定义的变量范围比使用 $解析
属性以外的更清洁的方式。我只是觉得我做这太困难了。
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.
全部Plunker 这里。
Full Plunker here.
推荐答案
为什么是一个孤立的范围矫枉过正?其pretty了整整这种事情有用:
Why is an isolate scope overkill? its pretty useful for exactly this kind of thing:
scope: {
"twoway": "=" // two way binding
},
这是一个pretty惯用的角度解决这个问题,所以这是我会坚持使用。
This is a pretty idiomatic angular solution to this problem, so this is what I'd stick with.
这篇关于AngularJS自定义指令双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!