我试图调用角度函数使用javascript / jQuery,下面是我发现的链接
> Call Angular Function with Jquery
> Call controller function from outside of controller component
我采取了相同的步骤,但在浏览器控制台中得到错误
Uncaught TypeError: Cannot call method 'myfunction' of undefined
我已经创建了fiddle.如何调用myfunction函数和警报显示?任何想法?
解决方法
解决方案在您链接的问题是正确的。实现的问题是您没有正确地指定元素的ID。
其次,你需要使用load事件来执行你的代码。目前DOM没有加载,因此元素没有找到,因此你得到错误。
HTML
<div id="YourElementId" ng-app='MyModule' ng-controller="MyController">
Hi
</div>
JS代码
angular.module('MyModule',[])
.controller('MyController',function ($scope) {
$scope.myfunction = function (data) {
alert("---" + data);
};
});
window.onload = function () {
angular.element(document.getElementById('YourElementId')).scope().myfunction('test');
}
DEMO