我对这个指令定义对象感到困惑 - (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/