javascript - 带有 "restrict"和不带 "restrict"的 Angular Directive(指令)

标签 javascript angularjs coffeescript

我对这个指令定义对象感到困惑 - (restrict)。 我创建了两个函数,第一个是带有 restrict 的函数,另一个是没有 restrict 的函数。

当我运行此代码时,两个指令返回相同的结果。

使用限制:

app.directive 'helloWorld', ->
  return {

    restrict: 'AE'
    link: (scope, elem, attrs) ->
       console.log "HELLO WORLD"

  }

没有限制:

app.directive 'helloWorld', ->
  return {

    link: (scope, elem, attrs) ->
       console.log "HELLO WORLD"

  }

有人能告诉我这是怎么回事吗? PS:我是 Angular 新手。拜托,如果您能帮我解决这个问题,我将不胜感激。

最佳答案

A directive can specify which of the 4 matching types it supports in the restrict property of the directive definition object.

默认是 EA。即,如果未指定限制。

限制选项通常设置为:

'A' - only matches attribute name
'E' - only matches element name
'C' - only matches class name
'M' - only matches the comment

这些限制都可以根据需要进行组合:

'AEC' - 匹配属性或元素或类名称 (ECA - 顺序无关紧要)

source - Angularjs 文档

app.directive 'helloWorld', ->
  return 
     restrict: 'AE' 
     link: (scope, elem, attrs) ->
        console.log "HELLO WORLD"

app.directive 'helloWorld', ->
    return
       link: (scope, elem, attrs) ->
          console.log "HELLO WORLD"

都是一样的,没有区别。两者都可以用作

<helloWorld> ... </helloWorld>

<ANY helloWorld> ... </ANY>

假设,如果您只有限制 E。那么指令功能仅适用于

<helloWorld> ... </helloWorld>

<ANY helloWorld> ... </ANY> // wont work since the directive is bound only to element

关于javascript - 带有 "restrict"和不带 "restrict"的 Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46358607/

相关文章:

javascript - Firebase 数组转换为 AngularChart

javascript - AngularJS:通过JS在输入框内写入,不传输JSON中的值

windows - 为什么我在 cygwin 中运行咖啡命令时出现错误?

javascript - 在 jupyter 笔记本中加载外部 javascript 库

javascript - 将选定的标签与右侧的 Kendo Multi-Select 对齐?

javascript - 我应该如何将 javascript 中的数组数组作为单值数组?

angularjs - ng-click 上 ng-model 值的更改

javascript - 如何将 dx-data-grid devexpress 导出为 pdf?

javascript - 更改哈希更改或导航、AngularJS、多个 View 上的部分 View