0

in my todo list i dont want user to input same todos again again... but my problem is, when i enter something for example (test) first time and than i enter (test2) and than i enter (test) again, so its taking a value.... how to validate properly....

fiddle https://jsfiddle.net/LaL7h6Lv/1/

html

<div ng-app="todoApp" ng-controller="mainCtrl">
        <ul>
          <li ng-repeat="todoItem in todoItems">{{todoItem.name}}</li>
        </ul>
    <form ng-submit="addItem()">
        <input type="text" ng-model="newItem">
        <input type="submit" name="go">
    </form>
    </div>

angularjs

angular.module("todoApp", [])
.controller('mainCtrl', ['$scope', function($scope){

  $scope.todoItems = [{'name' : 'akshay'}];
  $scope.test = false;

  $scope.addItem = function(){
      if($scope.newItem){
          $scope.checkRepeatTodo();
          if($scope.test == true){
              $scope.todoItems.push({'name':$scope.newItem});
              $scope.newItem = '';
          }else{
              alert('same todo');
              $scope.test = false;
          }
      }else{
          alert('fill the form');
      }
  };

  $scope.checkRepeatTodo = function(){
      $scope.todoItems.filter(function(item){
          if($scope.newItem === item.name){
              $scope.test = false;
          }else{
              $scope.test = true;
          }
      });
  };
}]);
0

1 Answer 1

1

The issue is with the $scope.test value, you override the value to true when it filters down the 3rd item.

See the Working fiddle

Alternative:

Make a javascript function rather than one in $scope and call that function return if its a valid entry or not.

This eliminates the need to have $scope.test and $scope.checkRepeatTodo as they do nothing of importance.

function checkRepeatTodo() {
  var valid = true;
     $scope.todoItems.filter(function(item){
       if($scope.newItem === item.name){
            return valid = false;
        }
    });
  return valid;
};

And use the same as:

if(checkRepeatTodo()){
    $scope.todoItems.push({'name':$scope.newItem});
    $scope.newItem = '';
}
else{
 alert('same todo');
}

Demo here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.