studentlisttest
by fresheyeball
HTML
<div ng-app>
<h1>Students List</h1>
<section ng-controller="StudentController">
<header>
<h2>Student Name</h2>
<h2>Grade</h2>
</header>
<ul>
<li ng-repeat="student in students" class="fail-{{(student.grade < 65)}}">
<input type="text" ng-model="students[$index].name"/><input type="number" ng-model="students[$index].grade" max="100" min="0" />
<button ng-click="delete($index)">X</button>
</li>
<div id="create" >
<input type="text" ng-model="newName" /><input type="number" ng-model="newGrade" max="100" min="0"/>
<button ng-click="create()" ng-disabled="validate()" >Create</button>
</div>
</ul>
<div>
Min : {{ min() }} | Max : {{ max() }} | Average : {{ avg() }}
</div>
</section>
</div>
CSS
body{
font-family:sans-serif;
white-space:nowrap;
}
section{
width:300px;
margin: 0 auto;
position:relative;
}
h2, input{
width:50%;
font-size:12px;
display:inline-block;
}
ul{
list-style:none;
padding:0;
}
input{
margin:0;
box-sizing:border-box;
padding:5px 10px;
border:1px solid black;
}
input:invalid{
border:2px dashed red;
}
li, #create{
background:grey;
padding:3px;
margin-bottom:2px;
border-radius:0 20px 20px 0;
}
header,li{
padding-right:45px;
}
#create{
padding-right: 75px;
width:252px;
}
.fail-true{
background:darkred;
}
button{
font-size:12px;
}
JavaScript
function StudentController($scope){
listKey = 'listKey';
storedStudents = localStorage.getItem(listKey);
$scope.students = (storedStudents)?JSON.parse(storedStudents):[];
$scope.delete = function(index){
if(confirm("Delete "+$scope.students[index].name+" ?")){
$scope.students.splice(index, 1);
}
};
$scope.clearFields = function(){
$scope.newName = ''; $scope.newGrade = '';
};
$scope.clearFields();
$scope.create = function(){
var newStudent = {
name : TitleCase($scope.newName),
grade : $scope.newGrade
};
$scope.clearFields();
$scope.students.push(newStudent);
};
$scope.validate = function(){
return (!$scope.newName || !$scope.newGrade);
};
$scope.minMaxAvg = function(minMaxAvg){
if($scope.students.length < 1){return 0;}
var grades = $scope.students.map(
function(el){ return el.grade; });
if($scope.newGrade){ grades.push($scope.newGrade); }
if(minMaxAvg == 'avg'){
var sum = grades.reduce(function(a, b) { return parseInt(a) + parseInt(b) }),
avg = (sum / grades.length);
return (avg)?avg.toFixed(1):0;
}else{
var val = Math[minMaxAvg].apply(Math, grades);
if(!val){ val = 0; }
return val;
}
};
$scope.min = function(){ return $scope.minMaxAvg('min'); };
$scope.max = function(){ return $scope.minMaxAvg('max'); };
$scope.avg = function(){ return $scope.minMaxAvg('avg'); };
$scope.$watch(function(){
localStorage.setItem(listKey, JSON.stringify($scope.students));
});
};
function TitleCase(str){
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}