【问题标题】:what is the use of a dollar ($) sign in angularjsangularjs中美元($)符号的用途是什么
【发布时间】:2016-04-17 23:05:49
【问题描述】:

我发现了一个类似的问题here,但要么我不明白答案,要么可能不是完全相同的问题。

components 的 angularjs 指南中,有多个视图示例,其中在 ctrl 变量之前使用 $ 符号,如下所示:

Name: {{$ctrl.hero.name}}<br>

在 heroDetails 控制器中,ctrl 变量前没有 $ 符号。如果我删除 heroDetails.html 中的 $ 符号,它就不再起作用了。

谁能给我解释一下?

提前感谢您的回答。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    当您创建Component 时,其控制器在视图中被标识为$ctrl

    Component documentation中引用:

                       -------------------------------------------------
                      |        Directive        |       Component       |
        --------------|-------------------------|-----------------------| 
       | controllerAs | Yes (default: false)    |  Yes (default: $ctrl) |
        ----------------------------------------------------------------
    

    符号 $ 是 Angular 为其自己的变量/属性使用的前缀。

    【讨论】:

      【解决方案2】:

      controller 属性是对控制器实例的引用,它将被组件使用。视图中控制器的名称是使用controllerAs 属性声明的。如果不注明controllerAs,则默认为$ctrl。所以 $ 符号只是名称的一部分。

      angular.module('heroApp').component('heroDetail', {
        templateUrl: 'heroDetail.html',
        controller: HeroDetailController, // the controller class
        controllerAs: 'whatever', // the controller alias in the view - default $ctrl
        bindings: {
          hero: '<',
          onDelete: '&',
          onUpdate: '&'
        }
      });
      

      【讨论】:

        猜你喜欢
        • 2022-04-11
        • 2010-11-05
        • 2011-03-28
        • 2015-10-23
        • 1970-01-01
        • 2020-01-20
        • 1970-01-01
        相关资源
        最近更新 更多