I am trying to push a shuffled string array to my scope variable, but some how its throwing error for duplicate array values. This never happened before.
Below is my code snippet. You can check the console for error:
var app = angular.module('ABCD', []);
app.controller('ABCDController', ['$scope',
function($scope) {
$scope.start_word = ['C', 'A', 'T'];
$scope.word = [
['C', 'A', 'T']
];
$scope.shuffle = function() {
var shuffle_word = Shuffle($scope.word[0]);
console.log("SHUFFLED VARIABLE: " + shuffle_word);
console.log("SCOPE VARIABLE: " + $scope.word);
$scope.word.push(shuffle_word);
};
}
]);
function Shuffle(o) {
for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<div ng-app="ABCD">
<div ng-controller="ABCDController">
<button class="btn btn-primary" ng-click="shuffle()">Shuffle</button>
<p>START WORD: {{start_word}}</p>
<p ng-repeat="(key,value) in word">SHUFFLED WORD: {{value}}</p>
</div>
</div>
My error is, when I try to push new shuffled value into the array, it changes all values to the new. For eg:
Initial array:
console.log($scope.word); OUTPUT: [['C','A','T']]
After push:
console.log($scope.word) OUTPUT: [['T','C','T'],['T','C','T']]
ng-repeat="(key, val) in x"
is the syntax for objects.. you wantng-repeat="letter in word"
for arrays. – tymeJV Mar 2 '15 at 17:49track by
clause:ng-repeat="letter in word track by $index"
– tymeJV Mar 2 '15 at 17:53