在 html 标签上声明 ng-app 和 ng-controller 是不好的

Is it bad to declare ng-app and ng-controller on html tag?

本文关键字:ng-controller ng-app html 标签 声明      更新时间:2023-09-26

<html>标签上同时声明ng-appng-controller是不好的做法吗?

例如:<html class="no-js" ng-app="myApp" ng-controller="MainCtrl">

这算不算不好的做法?我正在尝试动态控制应用程序的 <title> 标记,因此我想尽早声明MainCtrl控制器,因为它的范围在应用程序的其余部分中很重要。

然后,我可以在MainCtrl控制器中使用<title>{{settings.title}}</title>,并让子控制器通过$scope.$parent.settings.title = "hello world";访问它

您应该能够通过$window抽象访问和设置标题,从而消除了在html标签上放置控制器的需要。

我认为

到目前为止不会有任何问题。唯一的影响是根范围不再可从 html 标记中读取,因为控制器范围正在覆盖它。

例如

<div id="parent" ng-app>
  <div id="child" ng-controller='...'>
$rootScope.$id = 002    // rootscope from $rootscope service
$("#parent").scope().$id =002 // rootscope scope get from element scope    
$("#child").scope().$id =003  // controller scope get from element scope 

当涉及到相同的标记时,

<div id="parent" ng-app ng-controller='...'>
$rootScope.$id = 002    // rootscope from $rootscope service
$("#parent").scope().$id =003 // controller scope get from element scope

在这里,您无法从元素范围获取rootscope,但谁在乎呢。