Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
155 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...