angularjs - How to restrict from duplicate text field before pusing into array using Angular JS? -
i want restrict user create new text box , echo error message , if he/she inputs same value in previous text field. therefore create new text box if text fields has different values.
html
<input type="text" ng-model="set.values"/> <span ng-show="message"> please enter different value </span>
angularjs
$scope.set = { values: [] }; $scope.message = false; $scope.add = function (){ $scope.message = false; $scope.set.values.push(''); }
you can use indexof
, $watch
. watch ng-model
value change , check if value exists in array, if throw error.
html
<input type="text" ng-model="set.val"/> <span ng-show="message"> please enter different value </span>
js
$scope.set = { values: [] }; //array contains previous ng-model values $scope.message = false; $scope.$watch('set.val', function(val) { if (val != undefined) var index = $scope.set.values.indexof(val); if (index > -1) $scope.message = true; else { $scope.message = false; $scope.set.values.push(val); //add new input logic } })
update
if want check happen after clicking add button(which assume present in ui)
$scope.set = { values: [] //array contains previous ng-model values }; $scope.add = function() { var index = $scope.set.values.indexof($scope.set.val); if (index > -1) $scope.message = true; else { $scope.message = false; $scope.set.values.push($scope.set.val); //add new input logic } }
Comments
Post a Comment