我听说每个带有 ngApp 指令的 AngularJS 页面都有一个 Controller ,提供 $scope。在 W3Schools 给出的最早、最简单的示例中站点代码没有 ngController 标记:
<!DOCTYPE html>
<html lang="en-US">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="">
<p>Name : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
</div>
</body>
</html>
该页面显然有效——在 W3Schools 链接上尝试——并且有作用域($scope.name)。是否总有一个隐式 Controller ?
谢谢, 杰罗姆。
最佳答案
No there is not implicit controller there, behind the scene its
$rootScope
当您没有在 Angular ng-app
中指定 module
时,它将在没有 angular
模块的页面上初始化 angular。
但是因为你没有在这里提供 ng-controller
,Angular 将创建 $scope
,它将利用 $rootScope
,&将在 $rootScope
中创建变量。
因为每当您在页面上编写 ng-controller
指令时。 Angular 在当前运行的作用域上使用 $new(false)
方法从父 scope
创建新的作用域。在这种情况下,如果我们在这里引入 ng-controller
,那么它可能是 $rootScope.$new()
。
编辑
您可以通过使用 angular.injector
访问 $rootScope
来验证代码是否已添加到 $rootScope
代码
function checkScopeValues() {
var app = angular.element(document.getElementById('test')).injector();
var rootScope = app.get('$rootScope');
alert("value from rootScope " + rootScope.name);
}
关于javascript - 这个简单的 AngularJs 页面中的 Controller 在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32149101/