簡體   English   中英

如何在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM