在以下代码段中从ParentController中删除IIFE时,ParentController.apply()在ChildController中按预期工作。
但是,当ParentController在IIFE中时,ParentController.apply()在ChildController中不起作用,因为未定义ParentController。
我知道这是因为ParentController周围的IIFE正在从全局范围中删除它。我的问题是:如果仍然让ParentController.apply()正常工作(即 - 没有错误输出为'undefined'),如何将IIFE保留在ParentController和ChildController周围?
注意:我不想在我的解决方案中使用$ scope,所以在回答时不要建议与$ scope有什么关系。此外,ParentController和ChildController位于不同的文件中,因此将它们放在同一个IIFE中并不是一个有效的解决方案。
angular.module('app', []);
(function () {
'use strict';
angular
.module('app')
.controller('ParentController', ParentController);
function ParentController() {
var vm = this;
vm.hello = "Hello from Parent Controller!";
vm.helloAgain = function() {
return "Hello again from Parent Controller";
}
}
})();
(function () {
'use strict';
angular
.module('app')
.controller('ChildController', ChildController);
function ChildController() {
var vm = this;
vm.hello = "Hello from Child Controller!";
ParentController.apply();
vm.helloAgain = function() {
return parent.helloAgain();
}
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="ParentController as parent">
<h4>{{ parent.hello }}</h4>
<div ng-controller="ChildController as child">
<h4>{{ child.hello }}</h4>
<h4>{{ parent.hello }}</h4>
<!-- calls parent.helloAgain() from app.childController.js -->
<h1>{{ child.helloAgain() }}</h1>
</div>
</div>
</body>
答案 0 :(得分:1)
这可能很不错,但它似乎是你要求的:
angular.module('app', []);
(function () {
'use strict';
angular
.module('app')
.controller('ParentController', ParentController);
function ParentController() {
var vm = this;
vm.hello = "Hello from Parent Controller!";
vm.helloAgain = function() {
return "Hello again from Parent Controller";
}
vm.helloYetAgain = function() {
return "Hello AGAIN from Parent Controller";
}
}
})();
(function () {
'use strict';
angular
.module('app')
.controller('ChildController', ['$controller', ChildController]);
function ChildController ($controller) {
var vm = this;
var parent = $controller('ParentController');
parent.constructor.apply(this, arguments);
vm.hello = "Hello from Child Controller!";
vm.helloAgain = function() {
return parent.helloAgain.call(this);
}
}
})();
<body ng-app="app">
<div ng-controller="ParentController as parent">
<h4>{{ parent.hello }}</h4>
<div ng-controller="ChildController as child">
<h4>{{ child.hello }}</h4>
<h4>{{ parent.hello }}</h4>
<!-- calls parent.helloAgain() from app.childController.js -->
<h1>{{ child.helloAgain() }}</h1>
<h1>{{ child.helloYetAgain() }}</h1>
</div>
</div>
</body>
请注意,它不是真正的原型继承。