简体   繁体   中英

AngularJS - Calling function into a component

Im trying to call a function that I have into a component.

Here is the code from my component buttonsController:

(function(){
"use strict";

  angular
       .module('my')
       .component('myButton', {
        templateUrl: '../app/src/component/buttons.html',
        controller: buttonController,
        controllerAs: 'btnCmpnt',
        bindings: {
          newElement: '&',
          editElement: '&',
          deleteElement: '&',
          newTitle: '@',
          editTitle: '@',
          deleteTitle: '@'
        }
      });

  function buttonController($scope) {


      var vm = this;    

      vm.newElement =  () =>  {
        alert("1")
      }
      vm.editElement =  () =>  {
        alert("2")
      }
      vm.deleteElement =  () =>  {
        alert("3")
      }

  }

})();

Here is my buttons.html

<div class="col-md-12">
    <button ng-if="btnCmpnt.newTitle" title="Add configuration" class="btn btn-primary btn-md" ng-click="btnCmpnt.newElement()"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> {{btnCmpnt.newTitle}}</button>
</div>

And this is my html where I call my component:

<my-button new-title="New" new-element="newElement();"></my-button>

I can not do a call to my function.

Can you help me?

Regards!!

Well you never call binding method from inside of component. Instead you overwrite it with component controller method. This

vm.newElement = () => {
  alert("1")
}

will overwrite binding:

newElement: '&',

So you have two options. You either remove vm.newElement = () => { alert("1") } all together.

Or other option, if you want to have wrapper in controller. You rename it and call this.newElement() from inside:

vm._newElement = () => {
  alert("1")
  this.newElement() // call binding, outside function
}

In this case make sure you use new function name in template:

ng-click="btnCmpnt._newElement()"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM