angularjs – 使用Controller作为方法访问继承的作用域

前端之家收集整理的这篇文章主要介绍了angularjs – 使用Controller作为方法访问继承的作用域前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有了定义控制器的原始方式,访问父的范围是相当微不足道的,因为子范围原型继承自其父。
  1. app.controller("parentCtrl",function($scope){
  2. $scope.name = "Parent";
  3. })
  4. .controller("childCtrl",function($scope){
  5. $scope.childName = "child of " + $scope.name;
  6. });
  7.  
  8. <div ng-controller="parentCtrl">
  9. {{name}}
  10. <div ng-controller="childCtrl">
  11. {{childName}}
  12. </div>
  13. </div>

控制器 – 作为方法似乎是recommended的方式来声明控制器。但是使用Controller-As,上面的方法不再有效。

当然,我可以访问父范围与pc.name从视图:

  1. <div ng-controller="parentCtrl as pc">
  2. {{pc.name}}
  3. <div ng-controller="childCtrl as cc">
  4. {{cc.childName}}
  5. </div>
  6. </div>

我有一些问题(潜在的意大利面条代码),但这个问题是关于从子控制器访问父作用域。

我能看到这个工作的唯一方法是:

  1. app.controller("parentCtrl",function(){
  2. this.name = "parent";
  3. })
  4. .controller("childCtrl",function($scope){
  5. $scope.pc.name = "child of " + $scope.name;
  6. // or
  7. $scope.$parent.pc.name = "child of " + $scope.name;
  8.  
  9. // there's no $scope.name
  10. // and no $scope.$parent.name
  11. });

所以现在,子控制器需要知道“pc” – 除了,这应该(在我看来)被限制在视图。我不认为子控制器应该知道一个事实,一个视图决定宣布一个ng-controller =“parentCtrl as pc”。

Q:那么什么是正确的方法呢?

编辑:

澄清:我不想继承父控制器。我正在寻找继承/更改共享范围。所以,如果我修改第一个例子,我应该能够做到以下:

  1. app.controller("parentCtrl",function($scope){
  2. $scope.someObj = {prop: "not set"};
  3. })
  4. .controller("childCtrl",function($scope){
  5. $scope.someObj.prop = "changed";
  6. });
经过研究,我来到以下实现:

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。

这里有一个例子:

  1. var app = angular.module('myApp',[]);
  2.  
  3. // Then the controllers could choose whether they want to modify the inherited scope or not:
  4. app.controller("ParentCtrl",function($scope) {
  5. this.prop1 = {
  6. v: "prop1 from ParentCtrl"
  7. };
  8. $scope.prop1 = {
  9. v: "defined on the scope by ParentCtrl"
  10. };
  11. })
  12. .controller("Child1Ctrl",function($scope) {})
  13. .controller("Child2Ctrl",function($scope) {
  14. // here,I don't know about the "pc" alias
  15. this.myProp = $scope.prop1.v + ",and changed by Child2Ctrl";
  16. });
  1. <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
  2.  
  3. <body ng-app="myApp">
  4. <div ng-controller="ParentCtrl as pc">
  5. <div ng-controller="Child1Ctrl">
  6. <div>I know about the "pc" alias: {{pc.prop1.v}}</div>
  7. </div>
  8. <div ng-controller="Child2Ctrl as ch2">
  9. <div>I only care about my own viewmodel: {{ch2.myProp}}</div>
  10. </div>
  11. </div>

猜你在找的Angularjs相关文章