如何从jQuery调用Angular方法



这个问题类似于用Jquery调用Angular Function

但我认为我的例子有小不同。

Angular项目上,我有一个按钮:

<button id="button1" #tbName title="tbName" class="btn btn-lg btn-outline-primary" (click)="open(content,tbName.title)">Launch demo modal</button>

在TS文件上有一种方法:

open(content, title) {
console.log(document.getElementById('button1').getAttribute('title'));
this.id_desk = document.getElementById('button1').getAttribute('title');
this.modalService.open(content, { centered: true, container: '#test', ariaLabelledBy: 'modal-basic-title' }).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}

直接调用open(content,title)角度方法的jQuery函数应该是什么样子的?

我强烈建议你学习使用Angular(&w/o JQuery(,而不是混合两者。

现在我们在特种作战部队,你问了一些事情。你的代码有很多问题,但嘿,这不是我的项目,所以我会回答。

如果你想用JQuery访问一个Angular函数,像这样绑定到窗口。

ngOnInit() {
window['MyComponent']['open'] = this.open.bind(this);
}

现在在 JQuery 中,您可以使用

$(...).click(function() {
window.MyComponent.open('content of the modal', 'title of the modal');
});

通常,您不能触发在 和 Angular 组件中定义的方法,因为为此您需要类的实例。 请注意,您从不在代码中的任何位置调用new Component()? 相反,您只需指定类并将它们与模板绑定在一起,然后让 Angular 完成其余的工作。

也就是说,您可以将该方法作为对全局事物的引用传递。 例如,您可以执行以下操作:

class Component {
public fn () {} // <-- say you need this function
constructor () {
window.fn = this.fn.bind(this)
}
}

执行构造函数后,您将能够从任何文件调用window.fn()。 请注意,如果您希望具有组件的多个实例,则此方法将失败。 如果这样做,则需要将方法引用保存在数组或对象中。

也就是说,强烈建议不要这样做,因为它会使代码变得一团糟。

最新更新