我有一个内部带有功能的组件:
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>
该怎么做?
答案 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-if
或ng-repeat
包装的元素或组件时会发生这种情况。
使用“ controllerAs”语法实例化控制器可以避免该问题。
有关更多信息,请参见
注意:ng-ref
指令已添加到AngularJS V1.7.1 Momentum-Defiance