如何从外部操作组件控制器的功能 [英] How to operate functions of component controllers from outside

查看:52
本文介绍了如何从外部操作组件控制器的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a component with a function inside:

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

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

I would like to operate that function from outside the component:

<my-component>
</my-component>

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

该怎么做?

推荐答案

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

To access functions of component controllers, use the ng-ref directive:

<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将组件(或指令)的控制器分配给当前作用域中的给定属性.

The ng-ref directive tells AngularJS to assign the controller of a component (or a directive) to the given property in the current scope.

如果具有 ng-ref 的元素被破坏,则将 null 分配给该属性.

If the element with ng-ref is destroyed null is assigned to the property.

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

Note that if you want to assign from a child into the parent scope, you must initialize the target property on the parent scope, otherwise ng-ref will assign on the child scope. This commonly happens when assigning elements or components wrapped in ng-if or ng-repeat.

使用"controllerAs"语法实例化控制器可以避免该问题.

Instantiating controllers with "controllerAs" syntax obviates that problem.

有关更多信息,请参见

注意:: ng-ref 指令已添加到 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆