Encapsulating model in class for Angularjs application

I have 2 views. One of them is to list the student in the table, and the other when you click on the student, he shows the details of the student. I brought the student to him of his own class in a separate file student.js. The fact is that student details are not filled out in the submission.

I will present the controller and 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 studentDetailsCtrl:

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

This loadStudent()returns the ID of the current student from the URL and sets the student’s attributes.

View student details:

<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!

+4
1
<form name="student">

"" .

+1

Source: https://habr.com/ru/post/1654201/


All Articles