AngularJS Scope Object Inheritance -
hi need angularjs wiz point me in right direction been trying head around angularjs scope , inheritance. have child scope add parent scope want add new object parent scope via array.push(); i'm not sure why child scope inherits new value. see fiddle here http://jsfiddle.net/sjmcpherso/efxuz/ first example using ng-repeat , objects causes child update:
$scope.childarr = [{'name':'peter'},{'name':'paul'},{'name':'perry'}]; $scope.parentarr = $scope.childarr; $scope.parentarr.push({'name':'why in in child array?'}) whereas second example using variable not:
$scope.childvar = "confused muchly"; $scope.test.parentvar = $scope.childvar; $scope.test.parentvar = "this wont change child variable"; ideally make changes child scope update parent scope not other way around.
i have read of https://github.com/angular/angular.js/wiki/understanding-scopes while not understanding issue seems mystery me.
firstly, both of models $scope.childarr , $scope.test.parentarr in $scope of controller. none of them in parent scope.
if want have parentarr in parent scope, should have parent-child controller design or move model inside rootscope:
$rootscope.test = {}; $rootscope.test.parentarr = [ /* items here */ ]; secondly, $scope.childarr , $scope.test.parentarr both point same array. changing either of them mean changing both of them.
it same doing:
$scope.test = {}; $scope.childarr = $scope.test.parentarr = [ {'name':'peter'}, {'name':'paul'}, {'name':'perry'} ]; if want create separate copies changing 1 of them not affect other, can use angular.copy():
$scope.test.parentarr = angular.copy($scope.childarr);
Comments
Post a Comment