首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将模型封装在Angularjs应用程序自己的类中

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

Stack Overflow用户
提问于 2016-09-10 15:40:59
回答 1查看 58关注 0票数 4

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

我将为学生详细信息和学生类提供控制器和视图。

在student.js中作为工厂的学生原型

代码语言:javascript
复制
// 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中使用上面的学生原型

代码语言:javascript
复制
app.controller('studentDetailsCtrl', ['$scope', '$stateParams', 'Student', function($scope, $stateParams, Student) {
  $scope.student = new Student();
  $scope.student.loadStudent($stateParams.studentId);
}]);

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

学生详细信息视图:

代码语言:javascript
复制
<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>

​

我做错了什么?感谢您的帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-10 18:22:08

代码语言:javascript
复制
<form name="student">

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39423819

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档