somangshu Goswami somangshu Goswami - 1 month ago 5
AngularJS Question

Angularjs : 2 different scopes with same object data sharing same behaviour

I am making a nested tree structure with checkbox option in angularJs.

My object from the backend is as follows.

"2": {
"id": 2,
"name": "Under Graduate",
"slug": "under-graduate",
"parent_id": 0,
"level": 0,
"path": "0",
"show": false,
"selected": false,
"children": {
"3": {
"id": 3,
"name": "B.Com",
"slug": "b-com",
"parent_id": 2,
"level": 1,
"path": "2",
"show": false,
"selected": false,
"children": {
"4": {
"id": 4,
"name": "Commerce",
"slug": "commerce",
"parent_id": 3,
"level": 2,
"path": "2\/3",
"show": false,
"selected": false


I have assigned the same object to 2 $scope variable with different names

$scope.a = object;
$scope.b = object;

Now i have used ng-repeat inside the li element with ng-include as follows

<li ng-repeat="a in a.children" ng-include="'a_tree_renderer.html'"></li>

Using the same method with another variable(b)

<li ng-repeat="b in b.children" ng-include="'b_tree_renderer.html'"></li>

Inside both the template their is an option given to expand and view all the children.

Everything related to the tree algo works fine except when i perform this operation on one template ex. b, Somehow the template (a) index also changes, i.e if a expand an option from the second template the same thing on the first template expands, and vice versa.


By assigning $scope.a = object; and $scope.b = object;, both $scope.a and $scope.b reference the same object. Therefore, modifying one of them will affect the other.

If you would like $scope.a and $scope.b to be independent, you could create a deep copy of the object so that each scope variable references a different copy of the object, by using angular.copy. That way, when you change anything on $scope.a or $scope.b, the other will not be affected.