I have observed a strange behavior in JSON,
Let me try to describe scenario, we have one angular scope variable say
$scope.regValue = 0;
This is initialized in controller, and used under ngModel in HTML template to track down a change in value.
Now Let's assign this to JSON object key,
var jsonObj = {
'key1': $scope.regValue
};
What i have observed is, now
jsonObj['key1']
value will be 0 , which is Correct .
But when ngModel changes the value of $scope.regValue , It is not reflected under JSON key value, which means
jsonObj['key1']
is still equal to 0 .
While $scope.regValue has already changed.
Is this behavior expected, Or Pass by reference can't pass it's own reference to another variable ?
There is a difference in JavaScript between objects and primitive values (strings, numbers, booleans). Primitives are never passed by reference, while objects always are.
So in the case of your object property, you are assigning a numeric value to
var jsonObj = {
'key1': $scope.regValue // this is a number and assigned as such
};
When you update a property on the $scope
object , you are not modifying the value of the jsonObj
variable.
var $scope = { regValue: 0 } console.log($scope); console.log($scope.regValue); var jsonObj = { key1: $scope.regValue } console.log(jsonObj); console.log(jsonObj.key1); $scope.regValue = 5; console.log($scope); console.log($scope.regValue); console.log(jsonObj); console.log(jsonObj.key1);
Try this for comparison :
var otherObject = $scope;
You will see that otherObject
reflects all the changes of $scope
, because it is actually referencing the same object in memory.
var $scope = { regValue: 0 } console.log($scope); var otherObject = $scope; $scope.regValue = 5; console.log($scope); console.log(otherObject);
If you want to accomplish that 'second approach', use watchers:
$scope.$watch('regValue', function (newValue, oldValue, scope) {
jsonObj['key1'] = newValue ;
});
var jsonObj = {
'key1': $scope.regValue
};
// This function modifies the passed object.
var modify(obj) {
obj['key1'] = 12122;
};
modify(jsonObj); //jsonObj has a new value because was modified.
For instance, if a model ( $scope.regValue
) is attached to a input-text
and a user enters a new value, the $digest
's process will handle that information and assigns that data to the specific model $scope.regValue
. Therefore, the object jsonObj
is not modified because never was processed by the $digest
.
If you want the attribute key1
be modified when $scope.regValue
is modified by any process (ie: user input), use watchers
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.