得到孩子家长的控制器控制所有使用'控制器作为虚拟机“符号控制器、符号、虚拟机、家长

2023-09-13 05:08:26 作者:会有贱人替我害你i

父控制器设置为 parentCtrl为VM 和chield设置为 childCtrl为VMC 是没有名字的冲突,它工作得很好。

Parent controller set to 'parentCtrl as vm' and chield set to 'childCtrl as vmc' to be no name conflict and it works well.

如何才能在孩子控制器访问父控制器?

How can I get access to parent controller in child controller?

请注意,'$范围。$父母没有工作。

Note that '$scope.$parent' did not work.

推荐答案

要访问使用'$范围符号父控制器只使用'$范围。$父。

To access the parent controller using the '$scope' notation just use '$scope.$parent'.

然而,控制器VM符号缺乏细节,使得它与一些行为工作:

However the 'controller as vm' notation lacked a detail that makes it work with some behavior:

$范围。$父。 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文档中了解基本对象的副作用。

However changing the parent objects have side effects on primitive objects which may be understood in the following angular.js documentation.

JavaScript的原型继承

例如:

工作例如对JS斌

<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;
          };
        }
    ]);
})();