简体   繁体   English

AngularJS从子控制器访问父作用域

[英]AngularJS access parent scope from child controller

I've set up my controllers using data-ng-controller="xyzController as vm" 我使用data-ng-controller="xyzController as vm"设置我的控制器

I have a scenario with parent / child nested controllers. 我有一个父/子嵌套控制器的场景。 I have no problem accessing parent properties in the nested html by using $parent.vm.property , but I cannot figure out how to access the parent property from within my child controller. 通过使用$parent.vm.property访问嵌套html中的父属性没有问题,但我无法弄清楚如何从我的子控制器中访问父属性。

I've tried injecting $scope and then using $scope.$parent.vm.property , but this isn't working? 我已经尝试注入$ scope然后使用$scope.$parent.vm.property ,但这不起作用?

Can anyone offer advice? 有人可以提供建议吗?

If your HTML is like below you could do something like this: 如果您的HTML如下所示,您可以执行以下操作:

<div ng-controller="ParentCtrl">
    <div ng-controller="ChildCtrl">
    </div>
</div>

Then you can access the parent scope as follows 然后,您可以按如下方式访问父作用域

function ParentCtrl($scope) {
    $scope.cities = ["NY", "Amsterdam", "Barcelona"];
}

function ChildCtrl($scope) {
    $scope.parentcities = $scope.$parent.cities;
}

If you want to access a parent controller from your view you have to do something like this: 如果要从视图中访问父控制器,则必须执行以下操作:

<div ng-controller="xyzController as vm">
   {{$parent.property}}
</div>

See jsFiddle: http://jsfiddle.net/2r728/ 见jsFiddle: http//jsfiddle.net/2r728/

Update 更新

Actually since you defined cities in the parent controller your child controller will inherit all scope variables. 实际上,由于您在父控制器中定义了cities ,因此子控制器将继承所有范围变量。 So theoritically you don't have to call $parent . 所以理论上你不必叫$parent The above example can also be written as follows: 上面的例子也可以写成如下:

function ParentCtrl($scope) {
    $scope.cities = ["NY","Amsterdam","Barcelona"];
}

function ChildCtrl($scope) {
    $scope.parentCities = $scope.cities;
}

The AngularJS docs use this approach, here you can read more about the $scope . AngularJS文档使用这种方法, 在这里您可以阅读有关$scope更多信息。

Another update 另一个更新

I think this is a better answer to the original poster. 我认为这是原始海报的更好答案。

HTML HTML

<div ng-app ng-controller="ParentCtrl as pc">
    <div ng-controller="ChildCtrl as cc">
        <pre>{{cc.parentCities | json}}</pre>
        <pre>{{pc.cities | json}}</pre>
    </div>
</div>

JS JS

function ParentCtrl() {
    var vm = this;
    vm.cities = ["NY", "Amsterdam", "Barcelona"];
}

function ChildCtrl() {
    var vm = this;
    ParentCtrl.apply(vm, arguments); // Inherit parent control

    vm.parentCities = vm.cities;
}

If you use the controller as method you can also access the parent scope as follows 如果使用controller as方法,则还可以按如下方式访问父作用域

function ChildCtrl($scope) {
    var vm = this;
    vm.parentCities = $scope.pc.cities; // note pc is a reference to the "ParentCtrl as pc"
}

As you can see there are many different ways in accessing $scopes . 正如您所看到的,访问$scopes有许多不同的方法。

Updated fiddle 更新了小提琴

 function ParentCtrl() { var vm = this; vm.cities = ["NY", "Amsterdam", "Barcelona"]; } function ChildCtrl($scope) { var vm = this; ParentCtrl.apply(vm, arguments); vm.parentCitiesByScope = $scope.pc.cities; vm.parentCities = vm.cities; } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script> <div ng-app ng-controller="ParentCtrl as pc"> <div ng-controller="ChildCtrl as cc"> <pre>{{cc.parentCities | json}}</pre> <pre>{{cc.parentCitiesByScope | json }}</pre> <pre>{{pc.cities | json}}</pre> </div> </div> 

I've just checked 我刚检查过

$scope.$parent.someProperty

works for me. 适合我。

and it will be 它会

{{$parent.someProperty}}

for the view. 为了观点。

When you are using as syntax, like ParentController as parentCtrl , to define a controller then to access parent scope variable in child controller use following : 当您使用ParentController as parentCtrl as语法时,要定义控制器,然后在子控制器中访问父作用域变量,请使用以下命令:

var id = $scope.parentCtrl.id;

Where parentCtrl is name of parent controller using as syntax and id is a variable defined in same controller. 其中parentCtrl是使用as语法的父控制器的名称, id是在同一个控制器中定义的变量。

Some times you may need to update parent properties directly within child scope. 有时您可能需要直接在子范围内更新父属性。 eg need to save a date and time of parent control after changes by a child controller. 例如,需要在子控制器更改后保存父控件的日期和时间。 eg Code in JSFiddle 例如JSFiddle中的代码

HTML HTML

<div ng-app>
<div ng-controller="Parent">
    event.date = {{event.date}} <br/>
    event.time = {{event.time}} <br/>
    <div ng-controller="Child">
        event.date = {{event.date}}<br/>
        event.time = {{event.time}}<br/>
        <br>
        event.date: <input ng-model='event.date'><br>
        event.time: <input ng-model='event.time'><br>
    </div>
</div>

JS JS

    function Parent($scope) {
       $scope.event = {
        date: '2014/01/1',
        time: '10:01 AM'
       }
    }

    function Child($scope) {

    }

You can also circumvent scope inheritance and store things in the "global" scope. 您还可以规避范围继承并将事物存储在“全局”范围内。

If you have a main controller in your application which wraps all other controllers, you can install a "hook" to the global scope: 如果应用程序中有一个包含所有其他控制器的主控制器,则可以在全局范围内安装“钩子”:

function RootCtrl($scope) {
    $scope.root = $scope;
}

Then in any child controller, you can access the "global" scope with $scope.root . 然后在任何子控制器中,您可以使用$scope.root访问“全局”范围。 Anything you set here will be globally visible. 您在此处设置的任何内容都将全局可见。

Example: 例:

 function RootCtrl($scope) { $scope.root = $scope; } function ChildCtrl($scope) { $scope.setValue = function() { $scope.root.someGlobalVar = 'someVal'; } } function OtherChildCtrl($scope) { } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app ng-controller="RootCtrl"> <p ng-controller="ChildCtrl"> <button ng-click="setValue()">Set someGlobalVar</button> </p> <p ng-controller="OtherChildCtrl"> someGlobalVar value: {{someGlobalVar}} </p> </div> 

I believe I had a similar quandary recently 我相信最近我有类似的窘境

function parentCtrl() {
   var pc = this; // pc stands for parent control
   pc.foobar = 'SomeVal';
}

function childCtrl($scope) {

   // now how do I get the parent control 'foobar' variable?
   // I used $scope.$parent

   var parentFoobarVariableValue = $scope.$parent.pc.foobar;

   // that did it
}

My setup was a little different, but the same thing should probably still work 我的设置有点不同,但同样的事情可能仍然有效

From a child component you can access the properties and methods of the parent component with 'require'. 从子组件中,您可以使用“require”访问父组件的属性和方法。 Here is an example: 这是一个例子:

Parent: 家长:

.component('myParent', mymodule.MyParentComponent)
...
controllerAs: 'vm',
...
var vm = this;
vm.parentProperty = 'hello from parent';

Child: 儿童:

require: {
    myParentCtrl: '^myParent'
},
controllerAs: 'vm',
...
var vm = this;
vm.myParentCtrl.parentProperty = 'hello from child';

Super easy and works, but not sure why.... 超级容易和工作,但不知道为什么....

angular.module('testing')
  .directive('details', function () {
        return {
              templateUrl: 'components/details.template.html',
              restrict: 'E',                 
              controller: function ($scope) {
                    $scope.details=$scope.details;  <=== can see the parent details doing this                     
              }
        };
  });

Perhaps this is lame but you can also just point them both at some external object: 也许这是蹩脚的,但你也可以将它们都指向一些外部对象:

var cities = [];

function ParentCtrl() {
    var vm = this;
    vm.cities = cities;
    vm.cities[0] = 'Oakland';
}

function ChildCtrl($scope) {
    var vm = this;
    vm.cities = cities;
}

The benefit here is that edits in ChildCtrl now propogate back to the data in the parent. 这里的好处是ChildCtrl中的编辑现在传播回父节点中的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM