0

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>
iiian
  • 393
  • 1
  • 5
  • 17
  • 1
    get rid of using jQuery. This is not how to create angular app. Strongly suggest reading [thinking-in-angularjs-if-i-have-a-jquery-background](http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background) – charlietfl Sep 25 '16 at 18:18
  • @charlieftl thanks, good article. – iiian Sep 25 '16 at 18:33

1 Answers1

1

(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

Sajeetharan
  • 216,225
  • 63
  • 350
  • 396