有谁能请我提供简单的例子来更好地了解角度的父母和子女范围? 我尝试了以下内容,但它打印hello {{person}}作为输出。
<!DOCTYPE html>
<html>
<head>
<title> Simple app </title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js">
</script>
</head>
<body>
<h1 ng-app="MyApp3" ng-controller="ParentController">
<h1 ng-controller="ChildController">hello {{person}}</h1>
</h1>
</body>
<script>
var app=angular.module('MyApp3',[]);
app.controller('ParentController',function($scope)
{
$scope.person =
{
name : "Angular"
};
});
app.controller('ChildController',function($scope)
{
$scope.person.name="Angular";
$scope.person.age=40;
});
</script>
</html>
答案 0 :(得分:1)
我清理了一下你的代码。注意<div>
元素包含控制器范围。
您可以看到ChildController
如何访问ParentController
中的人,因为该对象显示的名称为“Child”,即使它位于ChildController
<div>
之外
var app=angular.module('MyApp3',[]);
app.controller('ParentController',function($scope)
{
$scope.person =
{
name : "Parent"
};
});
app.controller('ChildController',function($scope)
{
$scope.person.name="Child";
$scope.person.age=40;
});
<!DOCTYPE html>
<html>
<head>
<title> Simple app </title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js">
</script>
</head>
<body ng-app="MyApp3" ng-controller="ParentController">
<h1>This shows the object</h1>
<p>{{person}}</p>
<div ng-controller="ChildController">
<h1>This shows the name</h1>
<p>{{person.name}}</p>
</div>
</body>
</html>