[英]angularjs components. how to trigger functions from html
我有一个超级简单的组件。
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;
}
});
现在我想在名为my-component.html
文件夹elements/views
创建新的html
我猜是这样的:
<div ???="my-component.html">
<button ng-click="$ctrl.lol">Press it</button>
</div>
我该怎么办? 在HTML中,我该如何使这项工作?
我错过了什么?
长话短说,我需要制作删除按钮的组件,以防有人想要编写更多的代码。
您需要在控制器中将lol方法附加到此方法
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>
这是一个吸烟者
你可以尝试这样的事情:
<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)
这是一个小提琴:
你很近,但你只需要移动定义一些零碎的地方。
// 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()
(假设您打算将其定义为表达式? data: "&"
)
这是一个显示此示例的plunker: https ://plnkr.co/edit/yrFDMS?p = preview
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.