0

I have an object that contains a few properties and an array.

this._scope.SampleObject = {
    "Name": "Sample",
    "List": 
    [
        { 
            "Title": "Sample Title1",
            "HasValue": false 
        },
        { 
            "Title": "Sample Title2",
            "HasValue": false 
        }
    ]
}

Now once I pass this object in an ng-click directive, I use Object.create to create a separate instance of it.

//View
<button ng-click="Method(SampleObject)">Click</button>

// After the button above is clicked, a modal displays showing this HTML.
<div ng-repeat="item in Object2.List">
    <input type="checkbox" ng-model="item.HasValue" />
</div>

//Controller
$scope.Method = (SampleObject: any) => {
    this._scope.Object2 = Object.create(SampleObject);
}

My problem is that whenever I try to toggle the checkbox, the SampleObject is still the one being updated. Is there anything wrong with my code?

Thanks in advance for the help!

Josh Monreal
  • 754
  • 1
  • 9
  • 29
  • 1
    `Object.create()` does not operate recursively. The array that the `List` property refers to will still be the same for both objects. You'll want to research deep cloning/copying of objects. – Robby Cornelissen Jul 24 '18 at 10:17
  • In that case, how can I create a separate instance of the array (List)? – Josh Monreal Jul 24 '18 at 10:19
  • 1
    Personally I use lodash's [`cloneDeep()`](https://lodash.com/docs/4.17.10#cloneDeep). This [question](https://stackoverflow.com/questions/4459928/how-to-deep-clone-in-javascript) has some other alternatives. – Robby Cornelissen Jul 24 '18 at 10:20
  • 1
    Thank you. It seems that angular.copy can do the same job. – Josh Monreal Jul 24 '18 at 11:06

0 Answers0