Vaibhav Vaibhav - 3 months ago 9
AngularJS Question

Angularjs Validation is not working when it first time

I am new in angularjs and i am trying to do validate when submitting a form, its not working , but if i fill first input field and then submit it worked and then again clear that field its all clear how to clear this problem

Here is my html page

<form name="addAlbumForm" novalidate>
<div class="album panel panel-default" >

<div class="panel panel-heading">
<!-- <div class="alert alert-danger" role="alert" ng-show="addAlbumForm.date.$error.minlength">Date Too short</div> -->
<div class="alert alert-danger" role="alert" ng-show="addAlbumForm_error">{{addAlbumForm_error}}</div>
<input type="text" placeholder="Title...." size="20" ng-model="adding_album.title" style="width: 130px;"/>
<div class="panel-title" style="float: right">
<input type="text" name="date" ng-minlength="10" ng-required="true" placeholder="yyyy/mm/dd" size="10" ng-model="adding_album.date">
</div>

</div>
<p>
<div class="description">
<p>
<textarea ng-model="adding_album.description" placeholder="
Description..." rows="4" style="width:100%"></textarea>
</p>
<p> <input type="text" placeholder="Name..." size="10" ng-model="adding_album.name"></p>
</div>
</p>

<p >
<button type="button" ng-click="addAlbum(adding_album)" class="btn btn-success"> Add New Albums</button>
</p>
</div>




Here is my controller

MyApp.controller('AlbumListController', function($scope){
$scope.albums =[{ name: 'anand123', title: 'Weekend in Moderil',date:'12-01-2016',description :'abdkabkjasajsk sdsdsds dfdsfsdfsd '}]
$scope.addAlbum=function(new_album){
if(!new_album.title)
$scope.addAlbumForm_error= "Missing Title!";
else if(!new_album.date || new_album.date.length <10)
$scope.addAlbumForm_error= "Invalid Date!";
else if(!new_album.description || new_album.description <10)
$scope.addAlbumForm_error= "Description Too Short!";
else if(!new_album.name)
$scope.addAlbumForm_error= "Missing Name!";
else{
$scope.albums.push(new_album);
$scope.adding_album={};
}

}

});


i got error that Cannot read property 'title' of undefined, but once i fill title then it worked properly and also i cleared the title filed

Answer

you should try using ng-init in the form tag, initialize your variables such as adding_album as {} and addAlbumForm_error as false

for eg: <form ng-init="adding_album='{}'; addAlbumForm_error=false">