Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can controller talk to a directive in AngularJS?

  • I have a app that displays 4 flash cards, 3 of them are populated by one directive
  • for 1 last card, I would like the value to depend on a controller
  • Based on the view(and corresponding controller), controller can fill in the value of the 4th card.

  • For demo purposes, please see here

Question
- How can I update the value in the 4th card from some controller?
- Is it even a good idea to push values from some controller to directive?
- What could be the best possible solution?

I am Angular newbie and getting my head around it

like image 828
daydreamer Avatar asked Feb 15 '23 13:02

daydreamer


2 Answers

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

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

The 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, the easiest, if you want more info on directives there is also this excellent post : http://amitgharat.wordpress.com/2013/06/08/the-hitchhikers-guide-to-the-directive/

For the two other questions, yes, it could be a good idea to send data to a directive from a controller, it depends a lot on the data and the logic you want, but your app seems to need it.
The best solution doesn't exist (at least not with seeing only one simple example), but as it seems to be a simple data exchange, the easiest way to go seems to match your requirements ;)

Have fun

like image 104
DotDotDot Avatar answered Feb 27 '23 05:02

DotDotDot


The controller in the directive controls the scope of the directive. If you want to pass data from some other controller, then you have to pass from other controller via the controller in the directive.

There are couple of threads in stackoverflow relating how to pass data between controllers.

Hope this helps.

like image 31
zs2020 Avatar answered Feb 27 '23 06:02

zs2020