有了定义控制器的原始方式,访问父的范围是相当微不足道的,因为子范围原型继承自其父。
- app.controller("parentCtrl",function($scope){
- $scope.name = "Parent";
- })
- .controller("childCtrl",function($scope){
- $scope.childName = "child of " + $scope.name;
- });
- <div ng-controller="parentCtrl">
- {{name}}
- <div ng-controller="childCtrl">
- {{childName}}
- </div>
- </div>
控制器 – 作为方法似乎是recommended的方式来声明控制器。但是使用Controller-As,上面的方法不再有效。
当然,我可以访问父范围与pc.name从视图:
- <div ng-controller="parentCtrl as pc">
- {{pc.name}}
- <div ng-controller="childCtrl as cc">
- {{cc.childName}}
- </div>
- </div>
我有一些问题(潜在的意大利面条代码),但这个问题是关于从子控制器访问父作用域。
我能看到这个工作的唯一方法是:
- app.controller("parentCtrl",function(){
- this.name = "parent";
- })
- .controller("childCtrl",function($scope){
- $scope.pc.name = "child of " + $scope.name;
- // or
- $scope.$parent.pc.name = "child of " + $scope.name;
- // there's no $scope.name
- // and no $scope.$parent.name
- });
所以现在,子控制器需要知道“pc” – 除了,这应该(在我看来)被限制在视图。我不认为子控制器应该知道一个事实,一个视图决定宣布一个ng-controller =“parentCtrl as pc”。
Q:那么什么是正确的方法呢?
编辑:
澄清:我不想继承父控制器。我正在寻找继承/更改共享范围。所以,如果我修改第一个例子,我应该能够做到以下:
- app.controller("parentCtrl",function($scope){
- $scope.someObj = {prop: "not set"};
- })
- .controller("childCtrl",function($scope){
- $scope.someObj.prop = "changed";
- });
经过研究,我来到以下实现:
Controller-As approach is NOT a substitute for using
$scope
. Both have their place,and can/should be used together judicIoUsly.
> $ scope完全正是名称所暗示的:即它定义了$ scope上的viewmodel属性。这最适合与可以使用$ scope驱动自己的逻辑或更改它的嵌套控制器共享范围。
> Controler-As将整个控制器对象定义为具有命名范围的viewmodel(通过控制器的别名)。这最好只在视图(但不是其他控制器),如果视图决定是否要引用特定的控制器viewmodel。
这里有一个例子:
- var app = angular.module('myApp',[]);
- // Then the controllers could choose whether they want to modify the inherited scope or not:
- app.controller("ParentCtrl",function($scope) {
- this.prop1 = {
- v: "prop1 from ParentCtrl"
- };
- $scope.prop1 = {
- v: "defined on the scope by ParentCtrl"
- };
- })
- .controller("Child1Ctrl",function($scope) {})
- .controller("Child2Ctrl",function($scope) {
- // here,I don't know about the "pc" alias
- this.myProp = $scope.prop1.v + ",and changed by Child2Ctrl";
- });
- <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
- <body ng-app="myApp">
- <div ng-controller="ParentCtrl as pc">
- <div ng-controller="Child1Ctrl">
- <div>I know about the "pc" alias: {{pc.prop1.v}}</div>
- </div>
- <div ng-controller="Child2Ctrl as ch2">
- <div>I only care about my own viewmodel: {{ch2.myProp}}</div>
- </div>
- </div>