Questions And Answers

More Tutorials

Angular Avoid inheriting primitive values

In javascript, assigning a non-primitive value (Such as Object, Array, Function, and many more), keeps a reference (an address in the memory) to the assigned value.

Assigning a primitive value (String, Number, Boolean, or Symbol) to two different variables, and changing one, won't change both:

var x = 5;
var y = x;
y = 6;
console.log(y === x, x, y); //false, 5, 6

But with a non-primitive value, since both variables are simply keeping references to the same object, changing one variable will change the other:

var x = { name : 'John Doe' };
var y = x; = 'Jhon';
console.log( ===,,; //true, John, John

In angular, when a scope is created, it is assigned all of its parent's properties However, changing properties afterwards will only affect the parent scope if it is a non-primitive value:

angular.module('app', [])
.controller('myController', ['$scope', function($scope){
 $scope.person = { name: 'John Doe' }; //non-primitive
 $ = 'Jhon Doe'; //primitive
.controller('myController1', ['$scope', function($scope){}]);
<div ng-app="app" ng-controller="myController">
 binding to input works: {{}}<br/>
 binding to input does not work: {{name}}<br/>
 <div ng-controller="myController1">
 <input ng-model="" />
 <input ng-model="name" />

Remember: in Angular scopes can be created in many ways (such as built-in or custom directives, or the $scope.$new() function), and keeping track of the scope tree is probably impossible.

Using only non-primitive values as scope properties will keep you on the safe side (unless you need a property to not inherit, or other cases where you are aware of scope inheritance).


In this page (written and validated by ) you learned about AngularJS Avoid inheriting primitive values . What's Next? If you are interested in completing AngularJS tutorial, your next topic will be learning about: AngularJS Basic Example of scope inheritance.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.