siannone siannone - 7 months ago 34
AngularJS Question

Propagate changes from child to parent scope in AngularJS

I'm passing an object using an attribute from a parent scope to a child scope and I would like that changes made in the child scope are propagated to the parent scope.

Basically this is the parent view:

<foo oo-bar="object"></foo>

And this is

angular.module('foo').directive('foo', function()
return {
restrict : 'E',
templateUrl : ConfigService.path.views + '/table/projects.html',
scope : {
bar : '=ooBar'

The problem is that the changes made in the parent scope are propagated to the child scope but not the other way around.

For example, if I try to
$ = 4
in the child scope, the parent's
won't change.

What I understood is that Angular is creating a new
in the child scope that's not linked with the
in the parent's scope.

If that's the case, how can I propagate the changes back to the parent scope?

I thought that I could use a callback function, but I'm not sure that's the best way.

Edit: Plunker


The solution I was looking for I located here: Understanding Scopes

The key part is the following:

This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models – watch 3 minutes worth. Misko demonstrates the primitive binding issue with ng-switch.

Having a '.' in your models will ensure that prototypal inheritance is in play. So, use <input type="text" ng-model="someObj.prop1"> rather than <input type="text" ng-model="prop1">.

If you really want/need to use a primitive, there are two workarounds:

  1. Use $parent.parentScopeProperty in the child scope. This will prevent the child scope from creating its own property.
  2. Define a function on the parent scope, and call it from the child, passing the primitive value up to the parent (not always possible)