简体   繁体   English

AngularJS-将函数调用到组件中

[英]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: 这是我的组件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 这是我的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: 这是我在html中调用的组件:

<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. 您可以一起删除vm.newElement = () => { alert("1") }

Or other option, if you want to have wrapper in controller. 或其他选项,如果要在控制器中包含包装器。 You rename it and call this.newElement() from inside: 您将其重命名并从内部调用this.newElement()

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()"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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