Reputation: 28030
Inside my angularjs controller, I try to assign an object into a $scope.XX object. For some reason, it cannot work. Here is a simplified version of the code inside the angularjs controller.
$scope.XXX = {};
polling_interval_ms = 100;
var poll = function (ChartObj, polling_interval_ms) {
var processedObj = {};
processedObj = processDataChart(data_Chart); //data_Chart is object that contains data that changes in real-time
ChartObj = Object.assign(processedObj);
console.log(ChartObj);
$timeout(function () {
poll(ChartObj, polling_interval_ms)
}, polling_interval_ms);
};
poll($scope.XXX, polling_interval_ms);
console.log($scope.XXX);
The strange part is the output of console.log(ChartObj);
shows that data has been assigned to the object. However, the output of console.log($scope.XXX)
is empty. I was expecting $scope.XXX
to contain same data as ChartObj
. What did I do wrong?
Upvotes: 0
Views: 669
Reputation: 13381
In javascript all parameters in function is reference. So when you change reference - you not change referenced object.
In your case you can use Object.assgin in a bit different way
Object.assign(ChartObj, processedObj);
because
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
Or pass wrapper for object XXX, in this case it a $scope
$scope.ChartObj = {};
polling_interval_ms = 100;
var poll = function (wrapper, polling_interval_ms) {
var processedObj = {};
processedObj = processDataChart(data_Chart); //data_Chart is object that contains data that changes in real-time
wrapper.ChartObj = Object.assign(processedObj);
console.log(wrapper.ChartObj);
$timeout(function () {
poll(wrapper, polling_interval_ms)
}, polling_interval_ms);
};
poll($scope, polling_interval_ms);
console.log($scope.ChartObj);
Upvotes: 1
Reputation: 740
Use
$scope.XXX
instead of ChartObj because
your are assigning value to
ChartObj
and
$scope.XXX
is not a refrence type
Upvotes: 1