我正在学习inheritance in AngularJS
,所以我创建了一个挖掘它的例子。从上到下,它按预期传达信息。但是从孩子到父母不是。以下是我正在关注的tutorial使用$injector
。当我在我的代码中使用相同的代码时,它会让我知道我在这里做错了什么。
我的整个代码 -
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<title>Angular Inheritance</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<style>
html, body { text-align: center;}
div { border: 1px solid red; margin: 2px; padding: 2px;}
div div { border: 1px solid green; margin: 2px; padding: 2px;}
div div div { border: 1px solid blue; margin: 2px; padding: 2px;}
</style>
</head>
<body>
<div ng-controller="frstCtrl">
<p>I am <b>{{grandfather}}</b></p>
<p><b>{{father}}</b> is my son.</p>
<p><b>{{son}}</b> is my grandson.</p>
<div ng-controller="secCtrl">
<p>I am <b>{{father}}</b></p>
<p><b>{{grandfather}}</b> is my father.</p>
<p>{{son}} is my son</p>
<div ng-controller="thrdCtrl">
<p>I am <b>{{son}}</b></p>
<p><b>{{father}}</b> is my father.</p>
<p><b>{{grandfather}}</b> is my grandfather.</p>
</div>
</div>
</div>
</body>
</html>
<script>
var myApp = angular.module("myApp", []);
myApp.controller('frstCtrl', ['$scope', '$injector', function($scope, $injector){
$injector.invoke(thrdCtrl, this, {$scope: $scope});
$injector.invoke(secCtrl, this, {$scope: $scope});
$scope.grandfather = "Test GrandFather";
}]);
myApp.controller('secCtrl', ['$scope', '$injector', function($scope, $injector){
$injector.invoke(thrdCtrl, this, {$scope: $scope});
$scope.father = "Test Father";
}]);
myApp.controller('thrdCtrl', ['$scope', function($scope){
$scope.son = "Test Son";
}]);
</script>
答案 0 :(得分:3)
你还没有说它是如何破坏但是我假设你在使用secCtrl
和thrdCtrl
获得了一个ReferenceError?
如果您查看教程中的示例,您可以看到它们定义了一个名为CarController
的函数,然后在BMWController
中引用(通过闭包):
function CarController($scope) {
//...
}
function BMWController($scope, $injector) {
$injector.invoke(CarController, this, {$scope: $scope});
$scope.name = 'BMW';
}
您需要在示例中执行类似操作才能使其正常工作。
例如,将函数控制器定义为命名函数,然后在Angular中设置它们应该可以工作:
var myApp = angular.module("myApp", []);
myApp.controller('frstCtrl', ['$scope', '$injector', frstCtrl]);
function frstCtrl($scope, $injector){
$injector.invoke(thrdCtrl, this, {$scope: $scope});
$injector.invoke(secCtrl, this, {$scope: $scope});
$scope.grandfather = "Test GrandFather";
}
myApp.controller('secCtrl', ['$scope', '$injector', secCtrl]);
function secCtrl($scope, $injector){
$injector.invoke(thrdCtrl, this, {$scope: $scope});
$scope.father = "Test Father";
}
myApp.controller('thrdCtrl', ['$scope', thrdCtrl]);
function thrdCtrl($scope){
$scope.son = "Test Son";
}
如果您不清楚如何引用已命名的函数(frstCtrl
,srcCtrl
,thrdCtrl
)“之前”它们已被声明,请查看此博文关于变量和功能提升:http://designpepper.com/blog/drips/variable-and-function-hoisting