Update parent scope variable in AngularJS

Malcr001 picture Malcr001 · Jun 5, 2013 · Viewed 80.9k times · Source

I have two controllers, one wrapped within another. Now I know the child scope inherits properties from the parent scope but is there a way to update the parent scope variable? So far I have not come across any obvious solutions.

In my situation I have a calendar controller within a form. I would like to update the start and end dates from the parent scope (which is the form) so that the form has the start and end dates when submitted.

Answer

Dan picture Dan · Jun 5, 2013

You need to use an object (not a primitive) in the parent scope and then you will be able to update it directly from the child scope

Parent:

app.controller('ctrlParent',function($scope){
    $scope.parentprimitive = "someprimitive";
    $scope.parentobj = {};
    $scope.parentobj.parentproperty = "someproperty";
});

Child:

app.controller('ctrlChild',function($scope){
    $scope.parentprimitive = "this will NOT modify the parent"; //new child scope variable
    $scope.parentobj.parentproperty = "this WILL modify the parent";
});

Working demo: http://jsfiddle.net/sh0ber/xxNxj/

See What are the nuances of scope prototypal / prototypical inheritance in AngularJS?