How to operate functions of component controllers from outside

安稳与你 提交于 2019-12-12 06:49:10

问题


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>

How to do that?


回答1:


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>

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

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

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.

Instantiating controllers with "controllerAs" syntax obviates that problem.

For more information, see

  • AngularJS ng-ref Directive API Reference

Note: The ng-ref directive was added to AngularJS V1.7.1 Momentum-Defiance



来源:https://stackoverflow.com/questions/55976100/how-to-operate-functions-of-component-controllers-from-outside

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!