如何从外部操作组件控制器的功能

时间:2019-05-03 19:34:24

标签: angularjs angularjs-components

我有一个内部带有功能的组件:

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>

该怎么做?

1 个答案:

答案 0 :(得分:2)

要访问组件控制器的功能,请使用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被分配给该属性。

请注意,如果要从子级分配到父级作用域,则必须在父级作用域上初始化target属性,否则ng-ref将在子级作用域上分配。通常在分配用ng-ifng-repeat包装的元素或组件时会发生这种情况。

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

有关更多信息,请参见

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