David Faivre David Faivre - 1 year ago 94
AngularJS Question

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', [
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);

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
. I just feel like I'm making this too difficult.

Full Plunker here.

Answer Source

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.