angularjs – 使用Controller作为方法访问继承的作用域
有了定义控制器的原始方式,访问父的范围是相当微不足道的,因为子范围原型继承自其父。
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"; });
经过研究,我来到以下实现:
> $ scope完全正是名称所暗示的:即它定义了$ scope上的ViewModel属性。这最适合与可以使用$ 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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |