下面是使用范围继承的代码,
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Controller inheritance</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script type="text/javascript">
var sample = angular.module("sample", []);
function ParentController(){
this.Name = "Jag";
}
sample.controller("emp", ParentController);
function ChildController(){
this.Sal = 3500;
this.Dept = "Sales";
}
sample.controller("empDetails", ChildController);
</script>
</head>s
<body ng-app="sample">
<div ng-controller="emp as o1">
Employee details of <strong>{{o1.Name}}</strong>:
<div ng-controller="empDetails as o2">
<strong>{{o1.Name}}</strong> earns {{o2.Sal}} and works in {{o2.Dept}} department.
</div>
</div>
</body>
</html>
控制器实例的嵌套范围o2
必须参考Name
as o1.Name
.
下面是控制器继承的代码,
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> Scope inheritance</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script type="text/javascript">
var sample = angular.module("sample", []);
function ParentController(){
this.Name = "Jag";
}
sample.controller("emp", ParentController);
function ChildController(){
ParentController.call(this);
this.Sal = 3500;
this.Dept = "Sales";
}
ChildController.prototype = Object.create(ParentController.prototype);
sample.controller("empDetails", ChildController);
</script>
</head>
<body ng-app="sample">
<div ng-controller="emp as o1">
Employee details of <strong>{{o1.Name}}</strong>:
</div>
<div ng-controller="empDetails as o2">
<strong>{{o2.Name}}</strong> earns {{o2.Sal}} and works in {{o2.Dept}} department.
</div>
</body>
</html>
其中范围o2
不是嵌套的。
为了设计继承层次结构,AngularJS 推荐使用哪种方法?
注:术语控制器继承不是标准术语。
我不知道 AngularJS 推荐什么,但这是我的想法。
首先,我以前从未考虑过控制器继承。但现在我已经看到了它,我第一眼就能发现一些潜在的麻烦。
在这种情况下ParentController
没有依赖关系,所以事情进展顺利。但考虑到稍后您需要向其添加某种依赖项(服务),您必须记住在中请求该服务ChildController
然后将其传递给ParentController
用手。如果你问我的话,这是一个很大的烦恼。
如果我们看一下 html,第一种方式(正常范围继承)很明显:ChildController
确实需要ParentController
。第二种情况使事情变得更难看到,如果我查看 html,我发现两个控制器之间没有任何关系。
所以对我来说,范围继承(这实际上是默认的处理方式)在各个方面都优于控制器继承。
我相信 AngularJS 团队本身没有考虑过控制器继承(但不要因此而束缚我),所以最好坚持可验证的做事方式。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)