angularjs - 获取子 Controller 中的父 Controller ,所有子 Controller 都使用 'controller as vm' 表示法

标签 angularjs angularjs-controller

将父 Controller 设置为“parentCtrl as vm”,并将子 Controller 设置为“childCtrl as vmc”,以避免名称冲突,并且效果良好。

如何在子 Controller 中访问父 Controller ?

请注意,“$scope.$parent”不起作用。

最佳答案

要使用“$scope”表示法访问父 Controller ,只需使用“$scope.$parent”即可。

然而,“ Controller 作为虚拟机”符号缺乏使其适用于某些行为的细节:

'$scope.$parent.vm'

app.controller('childCtrl', [
    '$scope', function ($scope) {
        var vmc = this;

        // To protected access as vmc.parent
        Object.defineProperty(vmc, 'parent', {
            get: function () {
                return $scope.$parent.vm;
            }
        });
    }
]);

但是,更改父对象会对原始对象产生副作用,这可以在以下 angular.js 文档中理解。

JavaScript Prototypal Inheritance

示例:

Working example on JS Bin

<section class="parent" 
         data-ng-controller="parentCtrl as vm">
  <input data-ng-model="vm.name">

  <!-- have to change the prefix after the 'as' not to have conflict -->
  <section class="child"
           data-ng-controller="childCtrl as vmc">
    <input data-ng-model="vm.name">
    <!-- same results -->
    <input data-ng-model="$parent.vm.name">
    <!-- same results -->
    <input data-ng-model="vmc.parent.name">
    <!-- same results -->
    <button data-ng-click="vmc.changeName()">Change name</button>
  </section>
</section>
<小时/>
(function(){
  var app = angular.module('app', []);
  app.controller('parentCtrl', [
        '$scope', function ($scope) {
            var vm = this;
            vm.name = 'Julia';
        }
    ]);
  app.controller('childCtrl', [
        '$scope', function ($scope) {
            var vmc = this;

            // To protected access as vmc.parent
            Object.defineProperty(vmc, 'parent', {
                get: function () {
                    return $scope.$parent.vm;
                }
            });
          vmc.changeName = function(){
            vmc.parent.name = 'Other ' + vmc.parent.name;
          };
        }
    ]);
})();

关于angularjs - 获取子 Controller 中的父 Controller ,所有子 Controller 都使用 'controller as vm' 表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22966720/

相关文章:

javascript - Angular js中嵌入后的链接功能

javascript - AngularJS - 解码字节数组并播放音频文件(Wav/MP3)

angularjs - 使用 AngularJS 和 jsPlumb(在 AngularJS Controller 中使用 jsPlumb 函数)

javascript - 如何清除从 Controller 分配的事件?

angularjs - 在 Angular 中加载模块

javascript - AngularJS : cannot connect factory to controller

javascript - 如何在 AngularJS 中以编程方式触发表单提交?

angularjs - 使用 Angular JS 将数据插入 MongoDB

javascript - 如何在 Angular JS 中输入小时和分钟?

javascript - 尝试在 AngularJS 的 Controller 之间传递数据