How to operate functions of component controllers

2019-09-19 11:17发布

问题:

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