使用 jquery/javascript 调用 angularjs 函数 [英] Call angularjs function using jquery/javascript

查看:41
本文介绍了使用 jquery/javascript 调用 angularjs 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 javascript/jQuery 调用 angular 函数,以下是我找到的链接

我采取了相同的步骤,但在浏览器控制台中出现错误

未捕获的类型错误:无法调用未定义的方法myfunction"

我创建了小提琴.如何调用 myfunction 函数并显示警报?有什么想法吗?

解决方案

您链接的问题中提供的解决方案是正确的. 您的实施问题在于您没有指定 ID 元素正确.

其次,您需要使用 load 事件来执行您的代码.当前未加载 DOM,因此未找到元素,因此您收到错误.

HTML

你好

JS 代码

angular.module('MyModule', []).controller('MyController', function ($scope) {$scope.myfunction = 函数(数据){警报(---"+数据);};});window.onload = 函数 () {angular.element(document.getElementById('YourElementId')).scope().myfunction('test');}

演示

I am trying to call angular function using javascript/jQuery, following are the link I found

I have taken the same steps but getting error in browser console

Uncaught TypeError: Cannot call method 'myfunction' of undefined

I have created the fiddle. How to call myfunction function and alert is displayed? Any Idea?

解决方案

Solution provide in the questions which you linked is correct. Problem with your implementation is that You have not specified the ID of element correctly.

Secondly you need to use load event to execute your code. Currently DOM is not loaded hence element is not found thus you are getting error.

HTML

<div id="YourElementId" ng-app='MyModule' ng-controller="MyController">
    Hi
</div>

JS Code

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

这篇关于使用 jquery/javascript 调用 angularjs 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆