javascript - 将模型封装在 Angularjs 应用程序自己的类中

标签 javascript angularjs angularjs-scope javascript-objects angularjs-http

我有两个观点。一种是在表格中列出学生,另一种是当您单击学生时,它会显示学生的详细信息。我在单独的文件 student.js 中将学生带到了自己的类(class)。问题是,学生详细信息不会填充到 View 中。

我将与学生类(class)一起展示学生详细信息的 Controller 和 View 。

student.js 中作为工厂的学生原型(prototype):

// 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;
}]);

现在我在 studentDetailsCtrl 中使用上面的 Student 原型(prototype):

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

这里 loadStudent() 从 url 中获取当前学生的 id 并设置学生属性。

学生详情 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>

我做错了什么?感谢任何帮助!

最佳答案

<form name="student">

创建作用域表单变量“student”并重写您的学生模型。

关于javascript - 将模型封装在 Angularjs 应用程序自己的类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39423819/

相关文章:

javascript - 如果登录输入为空,则将用户重新定位到注册页面。 JavaScript

javascript - 如何在 Angular js 中创建动态工厂?

javascript - 使用 javascript 查找并替换 utf 字符

javascript - Ng-show 对范围变量变化没有反应

node.js - $http DELETE 变成 OPTIONS AngularJS

使用 Karma、Jasmine 和 ngHtml2JsPreprocessor 进行 AngularJS 测试指令 : template not loaded

Angular 4 : View is not updating after model change?

javascript - 我什么时候应该调用 $digest 而不是 $apply?

javascript - 一个 Controller 的作用域会阻塞 Angularjs 中的其他作用域

javascript - 在 Bootstrap 选项卡中加载谷歌地图,修复显示空白