我已经阅读了有关角$范围几个SO反应,以及它如何是一个普通的旧JavaScript对象,这意味着它会跟JS的原型继承(What are the nuances of scope prototypal/prototypical inheritance in AngularJS?)为什么我的Angular ngModel示例不会引发错误?
既然是这样的话,我很好奇,为什么我的下面的例子不会抛出一个错误:
<!doctype html>
<html ng-app='MyApp'>
<head>
<meta charset='utf-8'>
<title>Egghead</title>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js'></script>
<script>
var app = angular.module('MyApp', []);
app.controller('MainCtrl', ['$scope', function ($scope) {
}])
</script>
</head>
<body>
<div ng-controller='MainCtrl'>
<input type='text' ng-model='data.message'>
<p>{{ data.message }}</p>
</div>
</body>
</html>
基于原型继承,这是我所期望的发生:
- 当MainCtrl被调用时,它会创建为MainCtrl一个$范围对象及其相应的观点。
- 无论何时输入到输入框中,它都会将一些字符串绑定到$ scope.data.message。
- 但是,为了做到这一点,JavaScript中的第一步将尝试解决$ scope.data。
- 由于MainCtrl函数没有数据属性,它将尝试在rootScope中查找数据属性。
- 由于rootScope没有数据属性,$ scope.data应该解析为'undefined'。
- 最后,如果您尝试分配给undefined.message,则会引发错误。
但是,代码愉快地工作和数据绑定正确。有人可以帮助解开为什么这不是给我抛出一个错误?
把这个作为一个评论,因为我敢肯定有更多的技术响应。从我读过的内容来看,你是正确的,直到抛出错误。角色不是试图分配给undefined.message并抛出错误,而是检测到它是未定义的,并在该范围上创建它,然后分配该值。 –