使用jquery/javascript调用angularjs函数

MKB*_*MKB 46 javascript jquery angularjs

我试图使用javascript/jQuery调用角度函数,以下是我找到的链接

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

Uncaught TypeError: Cannot call method 'myfunction' of undefined
Run Code Online (Sandbox Code Playgroud)

我创造了小提琴.如何调用myfunction功能和警报?任何的想法?

Sat*_*pal 87

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

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

HTML

<div id="YourElementId" ng-app='MyModule' ng-controller="MyController">
    Hi
</div>
Run Code Online (Sandbox Code Playgroud)

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');
}
Run Code Online (Sandbox Code Playgroud)

DEMO


小智 32

您可以使用以下内容:

angular.element(domElement).scope() 获取元素的当前范围

angular.element(domElement).injector() 获取当前的应用程序注入器

angular.element(domElement).controller() 获取ng-controller实例.

希望可能有所帮助


Car*_*oth 9

另一种方法是在全局范围内创建函数.这对我来说是必要的,因为在Angular 1.5中无法达到组件的范围.

例:

angular.module("app", []).component("component", {
  controller: ["$window", function($window) {
    var self = this;
    
    self.logg = function() {
      console.log("logging!");
    };
    
    $window.angularControllerLogg = self.logg;
  }
});
               
window.angularControllerLogg();
Run Code Online (Sandbox Code Playgroud)


iva*_*rni 8

你的掠夺者正在开火

angular.element(document.getElementById('MyController')).scope().myfunction('test');
Run Code Online (Sandbox Code Playgroud)

在呈现任何内容之前.

您可以通过将其包装在超时中来验证它

setTimeout(function() {
   angular.element(document.getElementById('MyController')).scope().myfunction('test');    
}, 1000);
Run Code Online (Sandbox Code Playgroud)

您还需要在div中实际添加ID.

<div ng-app='MyModule' ng-controller="MyController" id="MyController">
Run Code Online (Sandbox Code Playgroud)