Ian Ian - 2 months ago 8
AngularJS Question

ng-repeat is slow to respond

I have an input box, which I am trying to tie to a div. This div outputs all the text values, separated by white space, previously entered into the input box.


  1. My first problem is that angularjs is slow to respond when outputting text entered into the box. When I press spacebar, the new element does not pop into the dom until I enter a new character into the input box.

  2. I am facing some strange bugs with this createNewTag function, where it dislikes me inputing multiple spaces in a row. Once 'bad data' is entered, the tool quits working, and an error is displayed- "Error: [ngRepeat:dupes]".



hope this is a fun one!

thanks.



function mainControllerCbk($scope) {
$scope.tags = [];
$scope.currentTag = "";
$scope.createNewTag = function(event) {
if (event.keyCode == 32) {
$scope.tags.push($scope.currentTag);
$scope.currentTag = "";
$('#entrybox').val('');
}
};
$('#entrybox').keyup($scope.createNewTag);
};

var app = angular.module('localApp', []);
app.controller('mainController', mainControllerCbk);

<!DOCTYPE html>
<html>

<head>
<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.23/angular.min.js"></script>
</head>
<body ng-app="localApp" ng-controller="mainController">
<div>
<input id="entrybox" data-ng-model="currentTag" />
<div id="tagsCollection" ng-repeat="tag in tags">
<span>{{tag}}</span>
</div>
</div>
</body>
</html>




Answer

(i)First issue is not because of ng-repeat, its because you are accessing element with jquery instead of doing a two way data binding, Add the new element to the collection by calling ng-blur directive which acts the same way lost focus,

<input name="myInput" ng-blur="createNewTag()" ng-model="currentTag" required>
  <div id="tagsCollection" ng-repeat="tag in tags track by $index">
    <span>{{tag}}</span>
</div>

(ii)Duplicate elements can be handled by adding this,

<div id="tagsCollection" ng-repeat="tag in tags track by $index">

DEMO

Comments