简体   繁体   English

如何在angularjs中仅使用类名从运行块调用控制器函数

[英]how to call controller function from run block only with classname in angularjs

I want to call controller function from run block.我想从运行块调用控制器函数。

HTML HTML

<div class="yourcontroller component section" ng-app="" data-ng-controller="mainController" data-module="yourcontroller">
</div>

And inside my run I'm trying to call the controller function like below在我的跑步中,我试图调用如下所示的控制器函数

var result = document.getElementsByClassName("yourcontroller");
var scope = angular.element(result);
scope.yourControllerMethod();

I'm getting yourControllerMethod is not defined我得到yourControllerMethod未定义

Please don't refer me the answer like below to use id instead of classname请不要向我推荐下面的答案来使用 id 而不是类名

 var scope = angular.element(document.getElementById('yourcontainer')).scope();
 scope.yourControllerMethod();

But I don't have id and I can't create id due to dependency.但是我没有 id 并且由于依赖关系我无法创建 id。 Is there anyway to call controller function from run block with the use of classname not with id .无论如何,是否可以使用classname 而不是 id从 run 块调用控制器函数。

Edit:编辑:

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();
        });

The getElementsByClassName(...) function returns a collection of elements not just one element. getElementsByClassName(...)函数返回一组元素,而不仅仅是一个元素。 To get the first element from this collection you can use [0] , eg: getElementsByClassName(...)[0] .要从此集合中获取第一个元素,您可以使用[0] ,例如: getElementsByClassName(...)[0] Beside that, you also have to call the yourControllerMethod() function on the angular element's scope not on the element itself.除此之外,您还必须在角度元素的范围而不是元素本身上调用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM