Angularjs inline two way binding

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

'=' sets up a two-way, but not literal, binding: instead of directly accepting a given value from the parent scope, it looks for a directive attribute with that name, then evaluates it, then uses the resulting value as the variable name of the parent object.

'@' sets up literal binding the way I want, but only one way.

I also tried '= @' in the hopes that Angular.js is smart enough to figure it out, but no luck.

I know that I can also use non-isolated scope (scope: true), but inside my code I use some methods that do not necessarily require isolated scope.

Is there a way to do what I want?

+3


source to share


2 answers


Passing the model across the scope between the Directive and the state is considered bad practice as it violates the Loose Coupling design principle. Means that it potentially makes Directives less reusable, has side effects in scope, and introduces obscure behavior. The same reasons are true when we talk about global state in JavaScript, which is also considered bad practice (but still available for some rare and specific cases).

I would recommend @

taking a closer look at attributes with a one-way interface. Because they actually provide a way to pass values ​​back and forth, and to maintain control over the Directive side. Don't be confused with terms :)

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

alert(theValueReturnsByController === 2);

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

      



In the template:

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

      

+3


source


It would be bad design if you could call it directly. Why not go through the bindings? You are explicitly using this method.



+1


source







All Articles