我试图学习 AngularJS 中的 Controller 继承。
请按照以下代码操作
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<title>Recipe 02 example 01</title>
<script type="text/javascript" src="D:\Rahul Shivsharan\JavaScript-Framework\AngularJS\angular.js"></script>
<script type="text/javascript" src="D:\Rahul Shivsharan\JavaScript-Framework\jQuery\jquery-1.11.1.js"></script>
<link rel="stylesheet" href="D:\Rahul Shivsharan\JavaScript-Framework\BootstrapCSS\bootstrap-3.2.0-dist\css\bootstrap.css"></link>
<script type="text/javaScript">
angular.module("myApp",[]);
(function(){
angular.module("myApp").controller("ParentCtrl",ParentCtrl);
angular.module("myApp").controller("ChildCtrl",ChildCtrl);
function ParentCtrl($scope){
$scope.lastName = "Bond"
};
function ChildCtrl($scope){
$scope.firstName = "James"
};
})();
</script>
</head>
<body>
<div ng-controller="ParentCtrl">
<div ng-controller="ChildCtrl">
<h3>Full name is {{firstName + " "+ lastName}}</h3>
</div>
</div>
</body>
上面的代码打印输出
Full name is James Bond
但是
如果我为 Controller 提供别名,它将不起作用,如下面的代码所示
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<title>Recipe 02 example 01</title>
<script type="text/javascript" src="D:\Rahul Shivsharan\JavaScript-Framework\AngularJS\angular.js"></script>
<script type="text/javascript" src="D:\Rahul Shivsharan\JavaScript-Framework\jQuery\jquery-1.11.1.js"></script>
<link rel="stylesheet" href="D:\Rahul Shivsharan\JavaScript-Framework\BootstrapCSS\bootstrap-3.2.0-dist\css\bootstrap.css"></link>
<script type="text/javaScript">
angular.module("myApp",[]);
(function(){
angular.module("myApp").controller("ParentCtrl",ParentCtrl);
angular.module("myApp").controller("ChildCtrl",ChildCtrl);
function ParentCtrl(){
var obj = this;
obj.lastName= "Bond"
};
function ChildCtrl(){
var obj = this;
obj.firstName = "James"
};
})();
</script>
</head>
<body>
<div ng-controller="ParentCtrl as p">
<div ng-controller="ChildCtrl as c">
<h3>Full name is {{c.firstName + " "+ c.lastName}}</h3>
</div>
</div>
</body>
输出为
Full name is James
我假设有一个从 ChildCtrl 到 ParentCtrl 的原型(prototype)链。 类似的东西
ChildCtrl.prototype = new ParentCtrl();
var c = new ChildCtrl();
console.log(" Full name is "+c.firstName+" "+c.lastName)
不是这样吗?
请解释一下或者给我一些指示。
最佳答案
两个片段之间的区别不仅仅是为 Controller 提供名称。在第一个示例中,您在 $scope
上设置属性。
function ParentCtrl($scope){
$scope.lastName = "Bond"
};
function ChildCtrl($scope){
$scope.firstName = "James"
};
而在第二个片段中,您在 Controller 本身上设置属性。
function ParentCtrl(){
var obj = this;
obj.lastName= "Bond"
};
function ChildCtrl(){
var obj = this;
obj.firstName = "James"
};
嵌套作用域确实继承原型(prototype)。嵌套 Controller - 不。因此,将第二个代码段更改为使用 $scope
即可,它会起作用。或者在引用属性时使用正确的 Controller (p.lastName
)。
要阅读的内容:https://github.com/angular/angular.js/wiki/Understanding-Scopes
关于javascript - 当我使用别名时,AngularJS 中的 Controller 继承不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31801586/