Search through JSON object with ng disabled (AngularJS)

One of the features of my web application is the ability to add new users (username + password) through the form. Thus, I have one JSON object ( l_usernames) defined in controller ( UsersController) with all user names already selected by users to avoid duplicate user names (this is a unique key).

An example of my data (fetched-data.json) is the format of the "usernames" ( l_usernames) object :

[{"0":"default","USERNAME":"default"},{"0":"user1","USERNAME":"user1"},{"0":"user2","USERNAME":"user2"},{"0":"user3","USERNAME":"user3"}]

There is an example form for adding new users (add-user.html):

<div class="row" ng-controller="UsersController">
  <div class="col-md-12">
    <div class="panel panel-primary">
      <div class="panel-heading">
        <h3 class="panel-title">Add New User</h3>
      </div>
      <div class="panel-body">
        <form class="form-horizontal" role="form">
          <div class="form-group">
            <label for="inputUserUsername" class="col-sm-2 control-label"><i class="icon fa fa-user"></i> USERNAME</label>
            <div class="col-sm-10">
              <input type="text" class="form-control" id="inputUserUsername" placeholder="Username" ng-model="user_username">
            </div>
          </div>
          <div class="form-group">
            <label for="inputUserPassword" class="col-sm-2 control-label"><i class="icon fa fa-key"></i> PASSWORD</label>
            <div class="col-sm-10">
              <input type="password" class="form-control" id="inputUserPassword" placeholder="Password" ng-model="user_password">
            </div>
          </div>  
        </form>
      </div>
    </div>
    <form class="form-inline">
      <div class="span7 text-center">
        <button type="submit" class="btn btn-success" ng-click="addUser()" ng-disabled="(!user_username || !user_password)">Save</button>    
      </div>
    </form>
  </div>
</div>

An example of my controller (userscontroller.js):

var app = angular.module('myApp');

app.controller('UsersController', ['$scope', 'services', function($scope, services) {     

services.getData().then(function(data){
  $scope.l_usernames = data.data;
});
}])

.factory('services', ['$http', function($http){
  var serviceBase = 'services/'
  var object = {};
  object.getData = function(){
    return $http.get('fetched-data.json');
  };
  return object;
}]);

, , - JSON l_usernames - ng-disabled ( "" ). - " " - . .

+4
2

scope_ userername. , JSON, lodash underscorejs l_usernames, , . , false. ng-disabled . debounce user_username .

function UsersController($scope) {
    $scope.name = 'Superhero';
    $scope.l_username = [{"0":"default","USERNAME":"default"},{"0":"user1","USERNAME":"user1"},{"0":"user2","USERNAME":"user2"},{"0":"user3","USERNAME":"user3"}];
    $scope.allowSave = true;
    $scope.$watch('user_username', function(value) {
      if (_.findWhere($scope.l_username, {"USERNAME": value}) !== undefined)
         $scope.allowSave = false;
         else
         $scope.allowSave = true;
    })
}

HTML

<button type="submit" class="btn btn-success" ng-click="addUser()" ng-disabled="!allowSave">Save</button>    

, , allowSave, "".

. underscore.js . .

.

+2

.

HTML:

<input username-exists type="text" ng-model="userName" ng-model-options="{updateOn: 'default blur', debounce: { 'default': 700, 'blur': 0 }}" />
<div ng-if="myFormName.$error.usernameExists">Username exists!</div>

<button type="button" ng-disabled="myFormName.$invalid">

ng-model-options , ( ).

JavaScript:

app.directive('usernameExists', function() {
    return {
        restrict: 'A', //match attributes only
        require: 'ngModel',
        scope: {
            l_usernames: '='
        },
        link: function(scope, elem, attrs, ctrl) {
            ctrl.$parsers.unshift(function(viewValue) {
                //first, assume the model is valid until proven otherwise
                ctrl.$setValidity('usernameExists', true);

                if(viewValue.length > 0 && !ctrl.$error.usernameExists) {

                    for(var i = 0; i < scope.l_usernames.length; ++i) {
                        if(scope.l_usernames[i].USERNAME === viewValue) {
                            //username exists, so set valididty to false
                            //the form is not valid
                            ctrl.$setValidity('usernameExists', false);
                            break; //found match
                        }
                    }
                }

                return viewValue;
            });
        }
    };
})
+1

All Articles