0

Hi I need a AngularJS Wiz to point me in the right direction been trying to get my head around AngularJS Scope and Inheritance. I have a child Scope which I add to a Parent Scope then I want to add a new object to the Parent scope via array.push(); but I'm not sure why the Child scope then inherits this new value. See the fiddle here http://jsfiddle.net/sjmcpherso/EFxuZ/ The first example using ng-repeat and objects causes the child to update:

$scope.childArr = [{'name':'peter'},{'name':'paul'},{'name':'perry'}];
$scope.parentArr = $scope.childArr;
$scope.parentArr.push({'name':'Why am I in now in the Child Array?'}) 

Whereas the second example using just a variable does not:

$scope.childVar = "Confused Muchly";
$scope.test.parentVar = $scope.childVar;
$scope.test.parentVar = "This wont change the child variable";

Ideally I would like to make changes to the child scope which would update the parent scope but not the other way around.

I have read of https://github.com/angular/angular.js/wiki/Understanding-Scopes while not fully understanding everything this issue seems a mystery to me.

1 Answer 1

2

Firstly, both of your models $scope.childArr and $scope.test.parentArr are in $scope of the controller. None of them is in parent scope.

If you want to have parentArr in the parent scope, then you should have a parent-child controller design or move your model inside the rootScope:

$rootScope.test = {};
$rootScope.test.parentArr = [ /* some items here */ ];

Secondly, $scope.childArr and $scope.test.parentArr both point to the same array. Changing either of them would mean changing both of them.

It is almost same as doing:

$scope.test = {};
$scope.childArr = $scope.test.parentArr = [
    {'name':'peter'},
    {'name':'paul'},
    {'name':'perry'}
];

If you want to create separate copies so that changing one of them would not affect the other, then you can use angular.copy():

$scope.test.parentArr = angular.copy($scope.childArr);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, yes my terminology is wrong they are in the same scope and yes i was ignoring JS prototype inheritance with the 2 objects and yes .copy() works perfectly. Thanks for clearing that up

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.