0

My controller

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

My 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

No fields are mandatory, i have to do a search function based on user inputs. I have to validate only one thing that user have to provide atleast one data. When i put console as above, i can see value in first one, whereas the .length console returns undefined.

enter image description here

Senthil Kumar J
  • 208
  • 2
  • 13

6 Answers6

1

There is no length property for an object. Use Object.keys length instead

Object.keys($scope.user).length;
KrishCdbry
  • 1,049
  • 11
  • 19
0

you should have to first assign initial values to your model by calling an ng-init function. in this function first set initial values for all your models other wise you will get this undefined error

Nitin Kumar
  • 898
  • 7
  • 22
0

You are trying to get length on an Object. There is no length property for an object. However you can get object length using Object.key(). Check details here.

get-js-object-length

Community
  • 1
  • 1
Md. Al-Amin
  • 1,423
  • 1
  • 13
  • 26
0

Your input type is "email" .

The value will not be assigned until you pass a valid email .

Make type email only for email fields , let rest be text.

To get the length :

Object.keys($scope.user).length;
bob
  • 4,595
  • 2
  • 25
  • 35
0

$scope.user is an object.Objects does not have length propertly.

If you want to get the number of properties of the object, then you have to use Object.keys(object).length function to get the length of properties of object.

ninjawarrior
  • 328
  • 1
  • 7
0

Here is the working fiddle of what are you trying to achieve.

Also, you cannot directly call the .length on an object. If you want to get the number of properties in the object try this SO Question.

Community
  • 1
  • 1
Shreyas
  • 1,927
  • 17
  • 34