0

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?

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Wonderful. I wish I can given you more points. Wonderful!!! I spent hours while you took minutes. You are a genius!!
@user16891328, just be more attentive when reading the documentation for the function :-)
1

Use

$scope.XXX   

instead of ChartObj because

your are assigning value to

ChartObj

and

$scope.XXX

is not a refrence type

Comments

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.