简体   繁体   English

AngularJS在ng-app范围之外运行?

[英]AngularJS running outside ng-app scope?

First, ng-app should be to set the area where angular take place, right? 首先, ng-app应该设置角度发生的区域,对吗? Even if there is ng-controller tag outside ng-app , they should be omitted? 即使ng-app外面有ng-controller标签,也应将其省略吗?

However, when I test on jsfiddle ( link here ), it seems this is not the case: 但是,当我在jsfiddle上测试( 链接在此处 )时,似乎并非如此:

HTML HTML

<div ng-app="myApp">
  <div ng-controller="MyCtrl">
    Hello, {{name}}!
    <input ng-model="name">
  </div>
</div><br><br>
<div class="not-inside-my-app">
  <div ng-controller="MyCtrl">
    ...... Some Many other content in real case that I don't want angular to touch .......<br>
    So this is to test angular is not working here.<br>
    Hello, {{name}}!
    <input ng-model="name">
  </div>
</div><br><br>
<div ng-app="myApp">
  <div ng-controller="MyCtrl2">
    Hello, {{name}}!
    <input ng-model="name">
  </div>  
</div>

Javascript 使用Javascript

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', ['$scope', MyCtrlFunction]);
function MyCtrlFunction($scope) {
    $scope.name = 'Superhero';
}

myApp.controller('MyCtrl2', ['$scope', MyCtrlFunction2]);
function MyCtrlFunction2($scope) {
    $scope.name = 'Non-superhero';
}

The angular code is still working in the middle div . 角度代码仍在中间div起作用。 Is my concept on ng-app wrong? 我对ng-app看法是否错误? Or what have I missed to limit the scope? 还是我错过了限制范围的东西?

PS I know I can control the scope by using ng-controller, but it seems to be a waste on resource to do scanning on sections that I know I don't need angularJS. PS我知道我可以使用ng-controller来控制范围,但是对我知道我不需要angularJS的部分进行扫描似乎浪费资源。

Since ng-app attribute added to body tag, which is why all controllers are running. 由于ng-app属性已添加到body标签,因此所有控制器都在运行。

Since angular considers first ng-app attribute and ignore other ng-app attributes. 由于angular首先考虑ng-app属性,而忽略其他ng-app属性。 The above code is working. 上面的代码正在工作。

NOTE: Though the code written in the html section didn't contain the body tag. 注意:尽管html部分中编写的代码不包含body标记。 You can able to insert the body tag by clicking on the gear icon in the html section of fiddle site. 您可以通过在小提琴网站的html部分中单击齿轮图标来插入body标签。 Which is what the main cause for this addition of ng-app attribute added to body tag. 这是将ng-app属性添加到body标签的主要原因。 Thanks for pointing it out Durga 感谢您指出杜尔加

屏幕截图在上面的小提琴链接中拍摄

在此处输入图片说明

remove body tag <body ng-app="myApp"> from html section, there is no issue with jsfiddle. 从html部分删除body标签<body ng-app="myApp"> ,jsfiddle没有问题。

JS jsFiddle似乎有问题,尝试在您的本地计算机上运行相同的示例,它将无法正常工作,或者您在这里得到了答案: https ://www.w3schools.com/code/tryit.asp?filename=FEYVPGYHZAY5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM