Tuesday, January 28, 2014

Angularjs example using ng-repeat and angular.forEach


dipslay json data into table and by using textbox add data to that table using input and submit.
and also restrict the duplicate entries:

<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">
<script src="http://code.angularjs.org/angular-1.0.0.min.js"></script>
<script src="http://code.angularjs.org/angular-resource-1.0.0.min.js"></script>
</head>
<body>
<div ng-app="wittyApp" id="ng-app" ng-controller="AvoidDuplicateEntries">
 
    <table class="table table-bordered">
<thead>
<tr>
<td>#</td>
<td>Movie Names</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="movie in movies">
<td>{{$index+1}}</td>
<td>{{movie.moviename}}</td>
</tr>
</tbody>
</table>
<br/>
<form ng-submit="add()">
<input type="text" placeholder="enter moviename" size="30" ng-model="moviename"/><br/>
<input type="submit" class="btn btn-primary"/>
</form>
 
 
</div>

<script>
var wittyApp=angular.module('wittyApp',[]);
function AvoidDuplicateEntries($scope) {
    $scope.movies = [
{moviename: "superman"},
{moviename: "spiderman"},
{moviename: "heman"}

];
  var somemovie=$scope.movies;
    $scope.add = function() {
   var newmovie=$scope.moviename;
   var oldmovie;
   if(newmovie){
   angular.forEach($scope.movies,function(eachmovie){
   if(newmovie==eachmovie.moviename){
   alert("moviename already exists");
   oldmovie=true;
   }
   });
 
   if(!oldmovie){
 
   somemovie.push({moviename:newmovie});
   $scope.moviename = "";
   }
 
   }
   }
}

</script>

</body>
</html>

No comments:

Post a Comment