vdudouyt
vdudouyt

Reputation: 936

Angularjs literal two-way binding

Is it possible to establish a two-way binding between parent scope and my directive's isolated scope, but without passing it through my directive's attributes?

'=' establishes a two-way, but not literal binding: instead of taking a specified value from the parent's scope directly, it looks for directive's attribute with a such name, then evaluates it, then uses a resulting value as a parent scope variable name.

'@' establishes a literal binding just as I want, but only one-way.

I've also tried '=@' in a hope that Angular.js is clever enough to understand that, but no luck.

I know that I can also use non-isolated scope (scope:true), but inside my code I'm using some techniques that necesarilly require an isolated scope.

Is there some way to do what I want?

Upvotes: 3

Views: 301

Answers (2)

Ilya Lakhin
Ilya Lakhin

Reputation: 1964

Passing a model through the scope between Directive and State considered as a bad practice because it violates Loose Coupling design principal. Means that it potentially makes Directives lesser reusable, have side effects in the scope, and introduces unclear behavior. The same reasons are true when we are talking about the global state in JavaScript which considered as a bad practice too(but still available for some rare and specific cases).

I would recommend to take a closer look in one-way bound @ attributes, though. Because, actually, they provide a way to pass values forward and backward as well keeping the control on the Directive side. Don't be confused with the terms :)

// in directive
var theValueReturnsByController = scope.myOneWayAttr({theValuePassedToController: 1});

alert(theValueReturnsByController === 2);

// in controller
scope.oneWayAttrHandler = function(theValueReceivedFromDirective) {
  theValueReturnedToDirective = theValueReceivedFromDirective + 1;
  return theValueReturnedToDirective;
};

In template:

<my-directive my-one-way-attr="oneWayAttrHandler(theValuePassedToController)"></my-directive>

Upvotes: 3

Florian Popa
Florian Popa

Reputation: 11

It would be a bad design if you could call it directly. Why not pass it through bindings? You explicitly use that method.

Upvotes: 1

Related Questions