【问题标题】:What is the best situation where you have to use a directive?必须使用指令的最佳情况是什么?
【发布时间】:2013-07-02 07:42:17
【问题描述】:

我目前正在为 angularJS 的一个大项目做准备,我真的对 angularJS 指令的用途感到困惑?

只是一个澄清,或者一个例子会真的很有帮助。

【问题讨论】:

标签: angularjs angularjs-directive


【解决方案1】:

你应该首先看看这个:http://blog.angularjs.org/2012/11/about-those-directives.html

也许你可以考虑像小宏这样的指令来改进经典的 HTML 语法。

指令用于将静态 HTML 元素替换为更模块化、可重用的部分功能。

想一个或多或少复杂的表格,它应该是动态的,并且您希望避免一直重新输入。这将是一个非常好的声明指令的场景。
指令是与 DOM 交互的唯一地方

当然,这只是一个非常基本的示例。对于懒惰的程序员来说,指令远不止是简写:)。它们可以为其他静态元素添加大量复杂性和功能,并且是实现 DRY 代码的好方法。

编辑:

您不仅可以通过创建自定义元素(如<myDirective>)来使用指令,还可以通过将它们限制为属性或类来使用指令。然后,您可以将函数链接到它们:

app.directive('myDirective',function(){
  return {
    restrict: 'A', // Attribute
    link: function(){
        // do something great
    }
  }
})

This 和其他关于指令的有趣内容(以及更多主题)在egghead.io 得到了很好的解释

进一步阅读和观看:

http://docs.angularjs.org/guide/directive
http://blog.brunoscopelliti.com/use-cases-of-angularjs-directives
http://www.codinginsight.com/angularjs-directives/
https://github.com/angular/angular.js/wiki/Understanding-Directives
http://www.befundoo.com/university/tutorials/angularjs-directives-tutorial/
http://www.egghead.io/

【讨论】:

  • 是的,我认为它也用于需要重复的代码,我想我会看看你提供的链接。谢谢 Sprrot!
【解决方案2】:

你应该先看看文档:http://docs.angularjs.org/guide/directive 然后看一些例子,比如这个只关注指令的例子:http://www.youtube.com/watch?v=Yg-R1gchccg

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2012-07-09
    • 1970-01-01
    • 2014-10-28
    • 2016-06-02
    • 1970-01-01
    • 2020-12-05
    相关资源
    最近更新 更多