检索AngularJS应用程序名称应用程序、名称、AngularJS

2023-09-13 05:12:47 作者:眼泪是回忆的常客

如何能在retrive的AngularJS当前应用程序的名称?结果我的意思是 NG-应用=富值。结果我已经通过API文档搜索,但我找不到这个任何引用。

How can I retrive the name of the current app in AngularJS? I mean the ng-app="foo" value. I have searched through the API documentation, but I could not find any reference to this.

我的解决方案结果这样其实我已经找到解决方案。

MY SOLUTION Actually I have found solution like this

angular.element($('[ng-app]')).attr('ng-app');  

但我真的不喜欢这个主意,通过DOM搜索只是为了得到这些信息。结果你知道一个更好的解决方案?

But I don't really like the idea to search through DOM just to get this information. Do you know a better solution?

推荐答案

从 $ rootElement的文档:

角应用程序的根元素。这可以是  其中,ngApp被宣布为元素或传递到元素  angular.bootstrap。

The root element of Angular application. This is either the element where ngApp was declared or the element passed into angular.bootstrap.

如果你注入它,你可以让主模块名而不扫描DOM:

If you inject it you can get the main module name without scanning the DOM:

<html ng-app="myApp">
...

app.controller('MyCtrl',
  [
    '$scope', 
    '$rootElement', 
    function($scope, $rootElement) {
      console.log($rootElement.attr('ng-app')); // --> myApp
    }
  ]
);