javascript
  • angularjs
  • 2017-04-11 32 views -1 likes 
    -1

    我目前正在嘗試使用AngularJS驗證一張卡片。直到用戶從輸入字段刪除所有輸入的數據也能正常工作的話,那將引發以下錯誤:AngularJS在獲取空輸入長度時拋出錯誤

    angular.js:11004 undefined is not an object (evaluating '$scope.card.length') 
    

    我的HTML代碼:

    拋出錯誤
    <input type="text" class='form-control' id='card' ng-model="card" ng-change="validateCard()" required> 
    

    JavaScript代碼,當輸入空:

    $scope.validateCard = function() { 
        // Get card type 
        if ($scope.card.length) { // <-- throws the error 
         [...] 
    

    我也試過

    if ($scope.card.length !== undefined) { 
    

    但它沒有幫助。

    +0

    '$ scope.card'也可能是未定義的。 'if($ scope.card && $ scope.card.length)''也許? – tanmay

    +1

    'if($ scope.card && $ scope.card.length)...' –

    回答

    2

    那是因爲你不能採取undefined值的長度。你可以使用這樣的事情:

    if ($scope.card && $scope.card.length) { } 
    
    0

    您可以同時檢查使用& &條件

    $scope.validateCard = function() { 
        if ($scope.card && $scope.card.length) { 
    } 
    
    0

    只要檢查您的項目定義:

    if (angular.isDefined($scope.card) && $scope.card.length) { } 
    
    相關問題