Wednesday, 18 September 2013

AngularJS Custom Directive Two Way Binding

AngularJS Custom Directive Two Way Binding

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();
});
}
};
}
])
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 here.

No comments:

Post a Comment