Sadeep Sadeep - 2 months ago 7
AngularJS Question

Encapsulating model in its own class for Angularjs app

I have 2 views. One is to list student in a table and the other is when you click on a student, it shows the details of the student. I have brought the student to it's own class in a separate file

student.js
. The thing is, student details don't get populated in the view.

I will present the controller and the view for student details along with the student class.

Student prototype as a factory in
student.js
:

// idea: You can initialize a student like new Student(student)
//where student is a json else new Student() will return a student with
//attributes set to null.

app.factory('Student', ['$http', function($http) {
function Student(student) {
if (student) {
this.setStudent(student);
} else {
this.setStudent({
id: null,
name: null,
level: null,
schoolName: null,
phoneNumber: null,
email: null
});
}
};
Student.prototype = {
setStudent: function(student) {
angular.extend(this, student);
},
loadStudent: function(studentId) {
var scope = this;
$http.get('myUrl/' + studentId).then(function(response){
scope.setStudent(response.data);
});
}
};
return Student;
}]);


Now I use the Student prototype above in the
studentDetailsCtrl
:

app.controller('studentDetailsCtrl', ['$scope', '$stateParams', 'Student', function($scope, $stateParams, Student) {
$scope.student = new Student();
$scope.student.loadStudent($stateParams.studentId);
}]);


Here
loadStudent()
takes the id of the current student from the url and set the student attributes.

Student Details view:

<div ng-controller="studentDetailsCtrl">
<div class="wrapper-md bg-light b-b">
<h1 class="m-n font-thin h3">Student Details</h1>
</div>
<div class="hbox hbox-auto-xs hbox-auto-sm">
<div class="col wrapper-md">
<form name="student" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2">Name: </label>
<div class="controls col-sm-5">
<p class="form-control-static">{{ student.name }}</p>
</div>
</div>
</div>
</form>
</div>
</div>




What am I doing wrong? Appreciate any help!

Answer
<form name="student">

Creates scope form variable "student" and rewrite your student model.

Comments