Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is it bad practice to declare both ng-app and ng-controller on the <html> tag?

For example: <html class="no-js" ng-app="myApp" ng-controller="MainCtrl">

Is this considered bad practice? I am trying to control the <title> tag of my application dynamically, so I want to declare the MainCtrl controller early as it's scope is important in the rest of the application.

Then I can use <title>{{settings.title}}</title> in the MainCtrl controller and have child controllers access it via $scope.$parent.settings.title = "hello world";

like image 269
Neil Avatar asked Oct 08 '13 17:10

Neil


People also ask

Can a HTML page have multiple NG App directive?

Only one ngApp directive can be auto-bootloaded per HTML Document but you can have multiple apps as long as you manually bootstrap the subsequent ones.

Can angular applications ng app be nested within each other?

AngularJS applications cannot be nested within each other. Do not use a directive that uses transclusion on the same element as ngApp . This includes directives such as ngIf , ngInclude and ngView .

What does ng app do?

The ng-app directive defines the root element of an AngularJS application and starts an AngularJS Application. The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded. It is also used to load various AngularJS modules in AngularJS Application.

Which is the correct syntax of creating AngularJS controller?

AngularJS Example The ng-controller="myCtrl" attribute is an AngularJS directive. It defines a controller. The myCtrl function is a JavaScript function. AngularJS will invoke the controller with a $scope object.


2 Answers

You should be able to access and set the title via the $window abstraction, thus removing the need to put a controller on the html tag.

like image 64
kontur Avatar answered Oct 11 '22 14:10

kontur


I don't think there will be any problem so far. The only impact is the rootscope no more readable from html markup, because the controller scope is overriding it.

For example,

<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  

when it comes to the same markup,

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

Here you have no way to get rootscope from element scope, but who cares.

like image 33
MJL Avatar answered Oct 11 '22 14:10

MJL