How can a controller talk to a directive in AngularJS?

  • I have an application that displays 4 flash cards, 3 of which are filled with one directive
  • for the last 1 card, I would like the value dependent on the controller
  • Based on the view (and the corresponding controller), the controller can populate the value of the 4th card.

  • For demo purposes see here

Question
- How can I update the value on the 4th card of some controller?
β€œIs it even a good idea to output values ​​from any controller to a directive?”
- What could be the best solution?

I am new to Angular and hug him.

+4
source share
2 answers

for your question, I think you need something like this: http://plnkr.co/edit/gp0zIwnj9Oz3IpQPXhDI?p=preview
I added data to the scope of your directive, this data is transmitted from the controller

scope: { ngModel: '=', somedata:'@' }, 

HTML:

 <data-ng-pt-header somedata='{{somedata}}'></data-ng-pt-header> 

And in the controller:

 $scope.somedata='This comes from the controller'; 

and of course in the template:

  <div class="well info-card days-left"> <legend>Spent</legend> <span>{{somedata}}</span> </div> 

This is one of the many ways to pass data to a directive, which is easiest if you want more information about the directives, there is this great post: http://amitgharat.wordpress.com/2013/06/08/the-hitchhikers-guide -to-the-directive /

For the other two questions, yes, it would be nice to send the data to the directive from the controller, it greatly depends on the data and logic that you need, but your application seems to need it.
The best solution does not exist (at least not having just one simple example), but it seems to be a simple data exchange, the easiest way seems to fit your requirements;)

Good luck

+7
source

The controller in the directive controls the scope of the directive. If you want to transfer data from some other controller, you need to switch from another controller through the controller in the directive.

There are several threads in stackoverflow related to transferring data between controllers.

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1497508/


All Articles