【问题标题】:Angular Directive with "restrict" and without "restrict"带有“restrict”和没有“restrict”的 Angular 指令
【发布时间】:2023-03-26 14:14:01
【问题描述】:

我对这个指令定义对象 - (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:我是角度的新手。请,如果您能帮助我,我们将不胜感激。

【问题讨论】:

    标签: javascript angularjs coffeescript


    【解决方案1】:

    指令可以在指令定义对象的限制属性中指定它支持的 4 种匹配类型中的哪一种。

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

    restrict 选项通常设置为:

    '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>
    

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

    <helloWorld> ... </helloWorld>
    

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

    【讨论】:

    • "默认为 EA。即,如果未指定限制。"谢谢@Sibi Raj。我现在清楚了。
    【解决方案2】:

    Restrict 指的是你的指令应该匹配的元素类型,并且不影响(以任何方式)你的指令的返回结果。来自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

    【讨论】:

    • 只是一个补充:OP的指令在有restrict: 'AE'和没有restrict: 'AE'的情况下都是一样的,因为指令的默认限制是'EA'
    【解决方案3】:

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

    <hello-world></hello-world>
    

    当您将E 值设置为您的restrict

    <ANY hello-world></ANY>
    

    当您设置A 值时。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 2011-08-14
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多