How do I refer to the scope of a parent inside a child controller when using the "as controller" syntax?

StackOverflow https://stackoverflow.com/questions/23568805

Вопрос

In my ParentController I currently have:

   $scope.grid = {
                $index: null,
                view: [],
                data: []
            };

In my ChildController I currently have:

   .controller('ChildController', ['$Scope',
        function ($Scope) {

            $Scope.grid.$index = null;
            $Scope.grid.view = [];
            $Scope.grid.data = [];

From what I understand this allows me to populate $Scope.grid.data in the ChildController and also have functions that can operate on the $Scope.grid.data inside the Parent Controller.

Now I would like to start using the "as controller" syntax. So if I understand this correctly I need to code inside the two HTML pages the controllers in my HTML like this:

<div data-ng-controller="ParentController as parent" ..

<div data-ng-controller="ChildController as child" ..

And my parent controller like this:

   this.grid = {
                $index: null,
                view: [],
                data: []
            };

If I do this then in my ChildController how should I refer to the grid.view? Do I somehow pass 'parent' into the ChildController and then in my child use:

parent.grid.view = [];

Finally I heard that the "as controller" syntax was experimental. Has it now got past that stage ?

Это было полезно?

Решение

As long as you don't change your code the "as" syntax doesn't make any difference.

If you changed ParentController to

this.grid = {
  $index: null,
  view: [],
  data: []
};

then you would still need a $scope reference in your ChildController, but you add another property:

   .controller('ChildController', ['$Scope',
    function ($Scope) {

        $Scope.parent.grid.$index = null;
        $Scope.parent.grid.view = [];
        $Scope.parent.grid.data = [];

As you can see it's not only more complicated, but you also couple the code to the HTML: If you decide to change your HTML to ParentController as someController your ChildController breaks.

So even with the "as" syntax you want grid to be a property of $scope.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top