2016-09-23 51 views
0

我控制器

App.controller('Ctrl', ['$scope', function ($scope) { 
    $scope.user = {}; 
    $scope.view = function() { 
       console.log($scope.user); 
       console.log($scope.user.length); 
    }]); 

我的HTML

<input type="text" ng-model="user.lastname" /> 
<input type="email" ng-model="user.email" /> 
<input type="text" ng-model="user.address" /> 
<input type="email" ng-model="user.id" /> 
<input type="text" ng-model="user.city" /> 
<input type="email" ng-model="user.country" /> ---> This will be a select 

任何字段是強制性的,我所要做的基於用戶輸入的搜索功能。我必須驗證用戶必須提供至少一個數據的一件事。當我把控制檯如上所述,我可以看到第一個值,而.length控制檯返回未定義。

enter image description here

回答

1

有一個對象沒有長度屬性。 使用Object.keys長度,而不是

Object.keys($scope.user).length; 
0

你應該通過調用一個函數ng-init首先分配初始值模型。在這個函數中首先設置所有模型的初始值,其他明智的你會得到這個未定義的錯誤

0

你想獲得一個對象的長度。對象沒有長度屬性。但是,您可以使用Object.key()獲取對象長度。在這裏查看詳情。

get-js-object-length

0

你的輸入類型爲"email"

該值將not be assigned,直到您通過一個有效的電子郵件。

僅對電子郵件字段進行類型電子郵件,讓其餘爲文本。

要獲取長度:

Object.keys($scope.user).length; 
0

$scope.user是object.Objects沒有長度propertly。

如果要獲取對象的屬性數量,則必須使用Object.keys(object).length函數來獲取對象屬性的長度。

0

以下是您正在努力實現的工作fiddle

此外,您不能直接調用對象上的.length。如果您想要 以獲取對象中的屬性數量,請嘗試此SO Question