UI_Dev UI_Dev - 2 months ago 20
AngularJS Question

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

I want to call controller function from run block.

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

Please don't refer me the answer like below to use id instead of classname

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. Is there anyway to call controller function from run block with the use of classname not with id.

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

Answer

The getElementsByClassName(...) function returns a collection of elements not just one element. To get the first element from this collection you can use [0], eg: getElementsByClassName(...)[0]. Beside that, you also have to call the yourControllerMethod() function on the angular element's scope not on the element itself.

// 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();
Comments