how to store same data in multiple $scope variables in same controller using angularjs

I have to store same data in two different scope variables. I have saved as per below code.

    app.controller('ClientsCtrl', function ($scope, $http) {

        $scope.model = {};

        $http.get("client/getdata", {})
            .then(function (result) {

                //For e.g, I have received result.data.Frequency = 'Weekly'

                $scope.model = {
                    edit: result.data,
                    show: result.data
                };

            },
            function (error) {
            });

    });

Used these scope variables to show and edit like

<div>        
    <div>
       Show Model Frequency: {{model.show.Frequency}}<br /><br />
       Edit Model Frequency: {{model.edit.Frequency}}
    </div>

    <div>
        <md-select ng-model="model.edit.Frequency" aria-label="Frequency">
            <md-option value="Daily"> Daily</md-option>
            <md-option value="Weekly"> Weekly</md-option>
        </md-select>
    </div>
</div>

If once I changed the value in edit model, its also auto change in show model even I stored in different variables.

I want to change the data only after save the data and don't want to display the changing frequency before save.

1 answer

  • answered 2018-04-17 05:34 Ramesh Rajendran

    Because of they have same reference. So you need to create a new reference before the object assignation.

    So use angular.copy

    $scope.model = {edit:angular.copy(result.data),show:angular.copy(result.data)};
    

    or try this

    $scope.model = {
                    edit:JSON.parse(JSON.stringify(result.data)),
                    show:JSON.parse(JSON.stringify(result.data))
                    };