【问题标题】:How to operate functions of component controllers from outside如何从外部操作组件控制器的功能
【发布时间】:2019-09-22 08:55:18
【问题描述】:

我有一个内部有函数的组件:

app.component("myComponent", {
    templateUrl: "myComponent.html",
    controller: function() {
        this.addApp = function (arg) {
            console.log(arg);
        };
    }
})

我想从组件外部操作该功能:

<my-component>
</my-component>

<button type="button" ng-click="something.addApp('Cheese')"
        class="btn-sm btn-default no-modal" >
  Add Application
</button>

怎么做?

【问题讨论】:

    标签: angularjs angularjs-components


    【解决方案1】:

    要访问组件控制器的功能,请使用ng-ref 指令:

    <div ng-controller="ctrl as vm">
        <my-component ng-ref="vm.myComponent1">
        </my-component>
    
        <button type="button" ng-click="vm.myComponent1.addApp('Cheese')"
                class="btn-sm btn-default no-modal" >
          Add Application
        </button>
    </div>
    

    ng-ref 指令告诉 AngularJS 将组件(或指令)的控制器分配给当前范围内的给定属性。

    如果带有ng-ref 的元素被销毁,则null 被分配给属性。

    注意,如果要从子作用域分配到父作用域,必须在父作用域上初始化目标属性,否则ng-ref 将在子作用域上赋值。这通常发生在分配包装在ng-ifng-repeat 中的元素或组件时。

    使用“controllerAs”语法实例化控制器可以避免这个问题。

    有关详细信息,请参阅

    注意:ng-ref 指令已添加到 AngularJS V1.7.1 Momentum-Defiance

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多