Angular 带 "restrict" 和不带 "restrict" 的指令

Angular Directive with "restrict" and without "restrict"

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

在我 运行 这段代码中,两个指令都返回了相同的结果。

restrict:

app.directive 'helloWorld', ->
  return {

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

  }

没有 restrict:

app.directive 'helloWorld', ->
  return {

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

  }

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

Restrict 指的是您的指令应匹配的元素类型,并且不会(以任何方式)影响您的指令的 return 结果。来自 angular docs:

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

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

'AEC' - matches either attribute or element or class name

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

The default 是 EA。即,如果未指定限制。

限制选项通常设置为:

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

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

'AEC' - 匹配属性或元素或 class 名称 (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>

说,如果你只有 restrict E。然后指令功能仅适用于

<helloWorld> ... </helloWorld>

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

一个小提示:如果你用驼峰命名你的指令,你需要在你的html代码中使用它时用-替换它,比如

<hello-world></hello-world>

当您将 E 值设置为 restrict

<ANY hello-world></ANY>

当您设置 A 值时。