如何从外部操作组件控制器的功能
我有一个内部带有功能的组件:
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
指令已添加到
查看更多