[AngularJS] Update Property in Parent Scope


When developing AngularJS application, sometimes we need to update properties in parent scope from child scope. Although properties inherited from parent scope are accessible from child scope, they cannot be updated directly from child scope. So how can we update properties in parent scope? After some Googling, I found that the event dispatching and listening mechanism in AngularJS can be used for our purpose. The following is an example demonstrating how to do:

Demo

event.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<!doctype html>
<html ng-app="event">
<head>
  <meta charset="utf-8">
  <title>AngularJS Update Parent Scope</title>
</head>
<body>

<div ng-controller="parentCtrl">
  The parentProperty value: {{ parentProperty }}
  <div ng-controller="childCtrl">
    <button ng-click="update()">click me to update parentProperty in parent scope</button>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
<script src="event.js"></script>
<!-- tested on 1.0.4 and 1.3.11 -->
</script>
</body>
</html>
event.js | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// tested on 1.0.4 and 1.3.11
angular.module('event', [])
  .controller('parentCtrl', ['$scope', function($scope) {
    $scope.parentProperty = 0;
    $scope.$on('updateParentScopeEvent', function(event, data) {
      $scope.parentProperty = data;
    });
  }])
  .controller('childCtrl', ['$scope', function($scope) {
    $scope.update = function() {
      $scope.$emit('updateParentScopeEvent', 1)
    };
  }]);

In this example, we have a property called parentProperty in parent scope. Initially the parentProperty is set to 0. When a user clicks on the button, an updateParentScopeEvent event will be dispatched from child scope to parent scope through $emit function. The parent scope registers a listener through $on function. In the listener, the property in parent scope is updated, which is the result we want.

This simple example demonstrates how to update properties in parent scope by event dispatching and listening. Hope this would be helpful!

Sample code tested on AngularJS 1.0.4 and 1.3.11


References:

[1]AngularJS: API: $rootScope.Scope
[2]AngularJS: Developer Guide: Scopes