How to reset scope data to initials value (Mini-challenge 3)

Mini-challenge 3

ng-challengeAngularJs Mini-Challenges is a growing collection of “Challenges” about the most quirky parts of the AngularJs framework. It encourage you to find and fix common mistakes and subtle bugs, as well as performance issues and bad practices, that non-expert AngularJs programmers may encounter on their endeavours into the depths of the framework.

AngularJs Mini-Challenges does not aim to teach you AngularJs. Former knowledge of the Framework is strongly recommended in order to understand the topics covered in this Challenges. In order to learn the basics of the Framework, please head over to this excellent book:

 

book

Book Tip

ng-book – The Complete Book on AngularJS
Ready to master AngularJS? What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall?


Amazon

 

The Challenge:

We have an Angular application where we want to create a starting point with the “default” data in the Angular scope, so we can create a reset button and restore the scope to the initial values.

the controller:

var myApp = angular.module('myApp', []);
myApp.controller('myCtrl',myCtrl);

function myCtrl($scope) {
    $scope.data = [{
        text: 'Lorem ipsum dolor sit amet',
        text2: 'consectetur adipiscing elit'
    }, {
        text: ' Nullam eu molestie mi',
        text2: 'Proin eu congue nisi.'
    }];

    $scope.origData = $scope.data;

    $scope.reset = function () {
        $scope.data = $scope.origData;
    };

}

This is the view:

<div ng-controller="myCtrl">
Modify the text in the inputs: 
<div ng-repeat="item in data"> <input type="text" ng-model="item.text"/> 
<input type="text" ng-model="item.text2"/> 
</div>
    <button type="button" ng-click="reset()">Reset</button>
</div>

Here is the fiddlejs: 

 

book

Book Tip

ng-book – The Complete Book on AngularJS
Ready to master AngularJS? What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall?


Amazon

 

The code example above is not working because when a JavaScript object (such as $scope.origData) is assigned to a variable, it is assigned by reference, not by value, the point of this challenge is to find a solution to make the reset button works.

Here you can find a possible solution

If you feel that the solution is poor or incomplete or there is room for improvement, please share with every one, you can leave a comment.