Issue
I need to get the previous value that was selected on a given ng-repeat so that I can return it back in case of business demand. How can I achieve this?
I have a ng-click, but at the point of the event click I already have the new item selected, but I need the old one too if it exists.
PS: I'm new to angular js, hence pardon my noobie question!
Thanks.
Solution
You can keep an array of the selections 'history'
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
let selHistory = []
$scope.selectThing = "val2"
$scope.recVal = function() {
if (selHistory.length === 0 || selHistory[selHistory.length - 1] !== $scope.selectThing)
selHistory.push($scope.selectThing)
console.log("The history of selections: ", selHistory);
}
$scope.recVal(); // push our intiial variable in there
$scope.revert = function() {
if (selHistory.length > 0) {
selHistory.pop();
$scope.selectThing = selHistory[selHistory.length - 1]
console.log("The history of selections: ", selHistory);
}
}
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-change="recVal()" ng-model="selectThing">
<option value='val1'>1</option>
<option value='val2'>2</option>
<option value='val3'>3</option>
</select>
<button ng-click='revert()'>Revert</button>
</div>
Answered By - Kinglish
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.