我正在尝试从超链接的 ng-click 调用 JavaScript 原型(prototype)函数,如下所示。但我无法在链接单击时触发 getInfo()
函数。我是否缺少任何基础知识或做错了什么?
这是我的 JS:
$(document).ready(function () {
function Apple() {
this.type = "fff";
this.color = "red";
}
Apple.prototype.getInfo = function () {
alert( this.color + ' ' + this.type + ' apple');
};
var appl = new Apple();
});
这是我的 html:
<a href="" ng-click="appl.getInfo()">click</a>
最佳答案
看看你上面的代码,我相信问题是你没有将appl
暴露给你的via(通过$scope
)。您需要做更多类似这样的事情:
var MyController = function($scope) {
function Apple() {
this.type = "fff";
this.color = "red";
};
Apple.prototype.getInfo = function () {
alert( this.color + ' ' + this.type + ' apple');
};
$scope.appl = new Apple();
};
然后:
<div ng-controller="MyController">
<a href="" ng-click="appl.getInfo()">click</a>
</div>
为了详细说明一下,像传递给 Angular 的 ngClick
这样的表达式是在 Angular $scope
的上下文中计算的(而不是在它们所在位置的上下文中) DOM)。您可以通过查看 source of ngClick
来看到这一点
关于javascript - 无法从 angularjs 调用 JavaScript 原型(prototype)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29359031/