[英]how to call controller function from run block with id in angularjs
[英]how to call controller function from run block only with classname in angularjs
我想从运行块调用控制器函数。
HTML
<div class="yourcontroller component section" ng-app="" data-ng-controller="mainController" data-module="yourcontroller">
</div>
在我的跑步中,我试图调用如下所示的控制器函数
var result = document.getElementsByClassName("yourcontroller");
var scope = angular.element(result);
scope.yourControllerMethod();
我得到yourControllerMethod
未定义
请不要向我推荐下面的答案来使用 id 而不是类名
var scope = angular.element(document.getElementById('yourcontainer')).scope();
scope.yourControllerMethod();
但是我没有 id 并且由于依赖关系我无法创建 id。 无论如何,是否可以使用classname 而不是 id从 run 块调用控制器函数。
编辑:
angular.module('modulename', [])
.controller('mainController', ['$scope', '$window', function ($scope, $window ) {
$scope.yourControllerMethod = function(){
console.log("inside yourControllerMethod");
};
}])
.run(function($rootScope, $log, $window) {
// get the first element with class 'yourcontroller'.
var result = document.getElementsByClassName("yourcontroller")[0];
// create a angular element from this element.
var aElm = angular.element(result);
// get this element's scope;
var scope = aElm.scope();
// call scope function.
scope.yourControllerMethod();
});
getElementsByClassName(...)
函数返回一组元素,而不仅仅是一个元素。 要从此集合中获取第一个元素,您可以使用[0]
,例如: getElementsByClassName(...)[0]
。 除此之外,您还必须在角度元素的范围而不是元素本身上调用yourControllerMethod()
函数。
// get the first element with class 'yourcontroller'.
var result = document.getElementsByClassName("yourcontroller")[0];
// create a angular element from this element.
var aElm = angular.element(result);
// get this element's scope;
var scope = aElm.scope();
// call scope function.
scope.yourControllerMethod();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.