这个简单的 AngularJs 页面中的控制器在哪里?
Where is the controller in this simple AngularJs page?
我听说每个 AngularJS 带有 ngApp 指令的页面都有一个控制器,提供 $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>
该页面显然有效——在 W3School link 上尝试——并且有范围($scope.name)。总是有一个隐式控制器吗?
谢谢,
杰罗姆.
此页面上没有控制器。但是 ng-controller
并不是创建 $scope 的唯一指令。 ng-app
还创建了一个 $scope,这就是 name
在
上的 $scope
控制器只是一些与范围交互的代码。
好吧,它只是 UI 中的一种简单的双向绑定,它实际上创建了控制器本身并将 $scope 绑定到您的指令:但在现实世界中,您必须创建一个模块,然后注入进入 it.This 的控制器只是让您体验一下 AngularJS 是什么,我在这里找到了 jenkov 的一个非常好的教程,它将指导您从头开始创建 AngularJs 应用程序
Link to the Tutorial
另外在 google 上搜索一些 AngularJs JsFiddle 示例,你可以找到很多帮助你入门的示例 –
No there is not implicit controller there, behind the scene its $rootScope
如果您没有在 angular ng-app
中指定 module
,它将在没有 angular
模块的页面上初始化 angular。
但是由于您没有在这里提供 ng-controller
,Angular 将创建 $scope
,它将利用 $rootScope
,并会在 [=11] 中创建变量=].
因为每当你在页面上写 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);
}
我听说每个 AngularJS 带有 ngApp 指令的页面都有一个控制器,提供 $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>
该页面显然有效——在 W3School link 上尝试——并且有范围($scope.name)。总是有一个隐式控制器吗?
谢谢, 杰罗姆.
此页面上没有控制器。但是 ng-controller
并不是创建 $scope 的唯一指令。 ng-app
还创建了一个 $scope,这就是 name
在
控制器只是一些与范围交互的代码。
好吧,它只是 UI 中的一种简单的双向绑定,它实际上创建了控制器本身并将 $scope 绑定到您的指令:但在现实世界中,您必须创建一个模块,然后注入进入 it.This 的控制器只是让您体验一下 AngularJS 是什么,我在这里找到了 jenkov 的一个非常好的教程,它将指导您从头开始创建 AngularJs 应用程序 Link to the Tutorial 另外在 google 上搜索一些 AngularJs JsFiddle 示例,你可以找到很多帮助你入门的示例 –
No there is not implicit controller there, behind the scene its
$rootScope
如果您没有在 angular ng-app
中指定 module
,它将在没有 angular
模块的页面上初始化 angular。
但是由于您没有在这里提供 ng-controller
,Angular 将创建 $scope
,它将利用 $rootScope
,并会在 [=11] 中创建变量=].
因为每当你在页面上写 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);
}