0

I'm following the conventions made by John Papa, but unfortunately I'm not really figuring out how to bind values from children controllers to parent controllers, using ui-router, ControllerAs and vm variables instead of $scope.

I made two examples, first example illustrates the working environment, so without ControllerAs and the normal $scope variable, this works, but when I change $scope to

var vm = this; 

it doesn't process any changes made to children controllers to the parent. I really want to make it work without working with some kind of PUBSUB pattern, because this is one of the most important features of working with two-way-data binding, but I don't know if this is possible within this situation?

I've created two Plunker examples to illustrate the problem:

Plunker example 1:

Plunker Example 2:

The first Example works, when changing some input fields within the template 'register-identification.html', this will directly change {{formData}} from the parent controller (RegisterBaseController).

The second Example doesn't process any changes.

I hope my explanation makes any sense? Hopefully someone can help me out!

Many thanks in advance!

Ken

KennyDope
  • 429
  • 1
  • 4
  • 13

1 Answers1

2

This scenario is behaving as expected, but not as you want.

$scope Inheritance - pass model by reference

The reason is, that any child state, is provided with prototypically inherited version of a $scope:

$childScope = $scope.$new();

And that means, that any reference created on parent is available on child

$scope.Reference = {};
$scope.Reference.A = 1;

$childScope = $scope.$new();
// here both contain 1 as Reference.A

$childScope.Reference.A = 2;

// both contain 2
$childScope.Reference.A === $childScope.Reference.A

hidding reference with another

But what you do (what controllerAs does) is:

$scope.vm = controllerParent;

$childScope = $scope.$new();

$childScope.vm = controllerChild;

The reference to vm itself is changed.

solution with a dot - Model {}

So, what could be working is combination:

$scope.Model = {}
$scope.Model.vm = controllerParent;

$childScope = $scope.$new();

$childScope.Model.childVm = controllerChild;
$childScope.Model.vm ... // this is parent controller 

Check the doc:

What Do Child States Inherit From Parent States?

and mostly:

Scope Inheritance by View Hierarchy Only

Keep in mind that scope properties only inherit down the state chain if the views of your states are nested. Inheritance of scope properties has nothing to do with the nesting of your states and everything to do with the nesting of your views (templates).

It is entirely possible that you have nested states whose templates populate ui-views at various non-nested locations within your site. In this scenario you cannot expect to access the scope variables of parent state views within the views of children states.

Check the dot in the model:

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335