控制器如何与 AngularJS 中的指令对话? [英] How can controller talk to a directive in AngularJS?

查看:29
本文介绍了控制器如何与 AngularJS 中的指令对话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 我有一个显示 4 张闪存卡的应用,其中 3 张由一个指令填充
  • 对于最后一张卡,我希望该值取决于控制器
  • 基于视图(和对应的控制器),控制器可以填写第四张卡片的值.

  • 出于演示目的,请参阅此处

问题
- 如何从某个控制器更新第四张卡中的值?
- 将值从某个控制器推送到指令是否是一个好主意?
- 最好的解决方案是什么?

我是 Angular 的新手,正在研究它

解决方案

对于你的问题,我认为你需要这样的东西:http://plnkr.co/edit/gp0zIwnj9Oz3IpQPXhDI?p=preview
我在你的指令范围内添加了数据,这个数据是从控制器传递的

范围:{ngModel: '=',一些数据:'@'},

HTML:

在控制器中:

$scope.somedata='这来自控制器';

当然在模板中:

 

<legend>花费</legend><span>{{somedata}}</span>

这是将数据传递给指令的众多方法之一,最简单,如果您想了解有关指令的更多信息,还有这篇出色的文章:http://amitgharat.wordpress.com/2013/06/08/the-hitchhikers-guide-to-the-指令/

对于另外两个问题,是的,从控制器向指令发送数据可能是个好主意,这在很大程度上取决于您想要的数据和逻辑,但您的应用程序似乎需要它.
最好的解决方案不存在(至少不是只看到一个简单的例子),但由于它似乎是一个简单的数据交换,最简单的方法似乎符合您的要求;)

玩得开心

  • 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

解决方案

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

这篇关于控制器如何与 AngularJS 中的指令对话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆