AngularJS conditional directive binds to child directive

Consider two nested directives with highlight areas:

<dctv1> <dctv2></dctv2> <dctv1> 

If I need dctv2 to talk to dctv1 , I have options:

  • I may need the dctv1 controller in the dctv1 definition using require:'^dctv1'
  • I can call an expression in the parent area with the wrapper <dctv2 callParent="hello()"></dctv2> and scope:{callParent:'&'}
  • I can also use $scope.$emit in dctv2 , but then all parent areas will hear this message.

Now I want dctv1 talk to dctv2 .

  • The only thing I can do is use $scope.$broadcast , but then all the children will hear.

Speaking here, I mean calling a function or the like. Do not want to set the clock clogging digestloop.

How can I make dctv1 notify dctv2 best way possible, making them relaxed? I should just delete dctv2 without errors.

+7
javascript angularjs
source share
4 answers

Check out AngularJS NgModelController for some ideas.

Each <dctv2> directive requires <dvtv1> to be entered into the controller. You can then add objects or callbacks to the properties of this controller and delete them when <dctv2> destroyed.

<dvtv1> will not talk directly to child elements, but will cause calls related to its properties.

For example;

NgModelController has $parsers and $formatters , which are an array of function callbacks. You insert your own functions into an array to extend the behavior of these controllers.

When the NgModelController performs input validation, it basically talks to other directives through these properties.

+3
source share

You can control it using an identifier for each child element that must be passed to the parent element; the parent will relay the event back using this id: the child will only perform the action if the identifier passed from the parent is its own.

Bye

0
source share

I would suggest using angular services . This way you can separate your behavior from one or more services.

See also this: AngularJS: how to look at utility variables?

0
source share

One way is to make a Service / Factory that will communicate with the controllers you want.

For example, here getter / setter Factory

 .factory('factoryName', function () { var something = "Hello"; return { get: function () { return something; }, set: function (keyword) { something = keyword; return something ; } }; }]) 

And then in your controllers:

 .controller('controllerOne', ['factoryName', function (factoryName) { $scope.test = factoryName.get(); }]); .controller('controllerTwo', ['factoryName', function (factoryName) { $scope.test = factoryName.get(); $scope.clickThis = function (keyword) { factoryName.set(keyword); }; }]); 

I suggest reading about this: Can one controller call another?

0
source share

All Articles