javascript - 为什么 'controller as' 不能直接从子 Controller 访问父作用域的属性?

标签 javascript angularjs controller

在阅读了几篇有关它的文章后,我打算将我的代码隐藏为使用 controller as 语法。然而,令我惊讶的是,使用 controller as 语法不能再直接使用父 Controller 的变量,我的意思是,以旧的方式(使用 $scope),我可以这样做:

// <div ng-controller="ParentCtrl">
//   <div ng-controller="ChildCtrl"></div>
// </div>
// 
app.controller('ParentCtrl', function ($scope) {
  $scope.x.title = 'Some title';
});


app.controller('ChildCtrl', function ($scope) {
  console.log($scope.x.title);
});

但是对于 controller as,我必须这样做(感谢这个 question ):

// <div ng-controller="ParentCtrl as pc">
//   <div ng-controller="ChildCtrl as cc"></div>
// </div>
// 
app.controller('ParentCtrl', function () {
  this.x.title = 'Some title';
});


app.controller('ChildCtrl', function ($scope) {
  console.log($scope.pc.x.title);
});

这很烦人,因为 1)。我必须知道在 html 页面中我的父 Controller 被命名为 pc。 2).我无法对 $scope => vm(或这个) 进行批量搜索和替换,因为如果属性是继承的,它将无法工作。

谁能告诉我引入 controller as 背后的基本原理是什么?

如果我使用大量作用域继承,那么我应该避免 controller as 吗?还是范围继承通常被认为是有害的并且应该被劝阻?

最佳答案

不,您不能进行机械搜索和替换,因为您当前将来自所有不同范围的值混合在一起,并且 controller-as 语法旨在将它们分开。它专门用于避免某些父作用域使用 title 然后您在子作用域中再次使用 title 并隐藏父作用域的情况。或者更糟的是,您认为您正在更新父 title,而实际上您所做的只是在一个子作用域中屏蔽它。

因此您必须实际计算出哪个父范围包含您要访问的每个值。这意味着如果您要将它从范围继承树中拉出,您确实必须知道用于引用该范围模型的名称。

更好的解决方案是使用指令,或者从 angular 1.5 开始的组件。而不是子 Controller 向上爬行以获取父值,而是将所需的值作为参数向下传递到指令/组件中。然后 parent 负责公开它希望 child 访问的值。或者,您可以使用指令或 Controller 的 require 属性创建一个仅在嵌入到特定父级中时才有效的子级,父级 Controller 将直接绑定(bind)到子级 Controller 。

这是来自 angular documentation 的示例.请注意,在 myPane Controller 中,您可以通过 this.tabsCtrl 访问父 Controller ,重要的是,决定父 Controller 使用什么名称的是子 Controller ,而不是父 Controller :

angular.module('docsTabsExample', [])
.component('myTabs', {
  transclude: true,
  controller: function MyTabsController() {
    var panes = this.panes = [];
    this.select = function(pane) {
      angular.forEach(panes, function(pane) {
        pane.selected = false;
      });
      pane.selected = true;
    };
    this.addPane = function(pane) {
      if (panes.length === 0) {
        this.select(pane);
      }
      panes.push(pane);
    };
  },
  templateUrl: 'my-tabs.html'
})
.component('myPane', {
  transclude: true,
  require: {
    tabsCtrl: '^myTabs'
  },
  bindings: {
    title: '@'
  },
  controller: function() {
    this.$onInit = function() {
      this.tabsCtrl.addPane(this);
      console.log(this);
    };
  },
  templateUrl: 'my-pane.html'
});

关于javascript - 为什么 'controller as' 不能直接从子 Controller 访问父作用域的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40746502/

相关文章:

javascript - 将自动化浏览器脚本制作成node.js

javascript - angular- 从范围 var 中获取 ng-model 名称

javascript - 在 JavaScript 函数中使用 AngularJS 值

java - Spring boot CORS 过滤器不适用于 AngularJS

php - Codeigniter:将数据从 Controller 传递到 View

java - 从 Spring Controller 下载文件

php - 代码点火器 2 : getting 404 error on default controller

java - 将 xml 转换为网格格式

javascript - 我认为我的网站已被感染

javascript - 仅在加载图像时才对图像应用阴影?