使用定义控制器的原始方法 ,访问父级的作用域非常简单,因为子级作用域原型继承自其父级。
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>
Controller-As方法 似乎是声明控制器的推荐方法。但是,对于Controller-A,上述方法不再有效。
当然,我可以通过pc.nameView 访问父作用域:
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"。
pc
ng- controller="parentCtrl as pc"
问: 那么什么是正确的方法?
编辑:
澄清:我不是要继承父控制器。我希望继承/更改共享范围。因此,如果要修改第一个示例,则应该能够执行以下操作:
app.controller("parentCtrl", function($scope){ $scope.someObj = {prop: "not set"}; }) .controller("childCtrl", function($scope){ $scope.someObj.prop = "changed"; });
经过研究,我得出以下认识:
Controller-As方法不能代替使用$scope。两者都有其位置,可以/应该明智地一起使用。
$scope
这是一个例子:
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>