angularjs组件。如何从html触发函数

时间:2018-04-13 12:00:12

标签: javascript angularjs

我有一个超级简单的组件。

app.component('myComponent', {
  bindings: {
    data: "&"
  },
  templateUrl: 'elements/views/my-component.html',
  controller: function() {

    const lol = function() {
      alert("You did it noob!");
    }

    $ctrl.$onInit = function() {
            $ctrl.lol = lol;
    }
});

现在我想在名为elements/views

的文件夹my-component.html中创建新的html

我猜是这样的:

<div ???="my-component.html">
  <button ng-click="$ctrl.lol">Press it</button>
</div>

我该怎么办?在HTML中,我该如何使这项工作?

我错过了什么?

长话短说,我需要制作删除按钮的组件,以防有人想要编写更多代码。

3 个答案:

答案 0 :(得分:3)

您需要将lol方法附加到控制器中的 this

angular.
  module('app',[]).
  component('myComponent', {
    template: '<div><button ng-click="$ctrl.lol()">Press it</button></div>',
    controller: function myCompCtrl() {
      this.lol = function() {
        alert("You did it noob!");
      };
    }
  });

然后在视图中

<div ng-app="app">
      <my-component></my-component>
    </div>

这里是plunker

答案 1 :(得分:0)

您可以尝试这样的事情:

<div ng-app="exampleApp">
   <example></example>
</div>

控制器:

var exampleComponent = {
    controller: function (){
      var ctrl = this;

      ctrl.doSomething = function () {
        alert('You are awesome');
      };
    },

    template: `
            <div>
              <button ng-click="$ctrl.doSomething();">
              Click me
              </button>
            </div>`
};


angular.module('exampleApp', [])
  .component('example', exampleComponent)

这是一个小提琴:

https://jsfiddle.net/1h07t30z/755/

答案 2 :(得分:0)

你很接近,但你只需要移动定义一些零碎的地方。

scala> "mississippi".distinct
res22: String = misp

您也可以在组件模板中调用// In your .js file app.component('myComponent', { bindings: { data: "&" }, templateUrl: 'elements/views/my-component.html', controller: function() { /* Note that inside your controller function you just use `this` to refer to it - it's a regular JavaScript constructor function. In your template you can reference the controller with `$ctrl`. */ this.lol = function() { alert("You did it noob!"); } this.$onInit = function() { } } }); <!-- elements/views/my-component.html --> <button ng-click="$ctrl.lol()">Press it</button> <!-- In your main application template (*outside* my-component.html) --> <my-component> </my-component> 绑定data(假设您打算将其定义为表达式?$ctrl.data()

这是一个显示此示例的plunker: https://plnkr.co/edit/yrFDMS?p=preview