2016-05-04 63 views
4

我的web應用程序的功能之一是可以通過表單添加新用戶(用戶名+密碼)。因此,我在控制器(UsersController)中定義了一個JSON對象(l_usernames),用戶已經選擇了所有用戶名以避免重複使用用戶名(它是唯一鍵)。我的數據使用ng-disabled(AngularJS)搜索JSON對象

樣品(取-data.json) - 對象的格式爲 「用戶名」(l_usernames):

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

有以下形式的樣品添加新用戶(添加 - 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> 

樣品(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-禁用(通過禁用「保存」按鈕) 。我也想打印一個簡單的信息 - 「已經選擇的用戶名」 - 如果發生這種情況。謝謝。

+0

您可以創建一個指令來檢查輸入的值在JSON已經存在,並且相應地設置輸入驗證。然後,如果表單無效,只需禁用該按鈕 – yBrodsky

回答

2

在user_username範圍變量上添加監視。只要它通過JSON對象更改搜索,就可以使用lodash或underscorejs搜索l_usernames以查看用戶名是否已存在。如果存在,則在範圍內設置一個變量爲false。將保存按鈕的ng-disabled綁定到該變量。在user_username上使用debounce以獲得更好的性能。

看看這個小提琴here

控制器

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來搜索列表。您也可以使用自定義方法。

我添加了警告消息並消除了模型以獲得更好的性能。

+0

非常感謝。我將編輯我的帖子以添加更多關於如何獲取我的數據的信息。 – Ariana

+0

一旦你得到了l_usernames數組,上面的代碼應該可以工作。 –

+0

非常感謝:D它的工作完美。 – Ariana

1

我會做一個驗證指令。

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; 
      }); 
     } 
    }; 
}) 
+0

謝謝。這似乎是我的問題的一個很好的解決方案,但我已經實施了另一個。乾杯! – Ariana