【发布时间】:2017-01-18 07:51:25
【问题描述】:
我有 2 个视图。一种是在表格中列出学生,另一种是当您单击学生时,它会显示学生的详细信息。我在单独的文件student.js 中将学生带到了自己的班级。问题是,视图中不会填充学生详细信息。
我将与学生班级一起展示控制器和学生详细信息的视图。
学生原型在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;
}]);
现在我在studentDetailsCtrl中使用上面的Student原型:
app.controller('studentDetailsCtrl', ['$scope', '$stateParams', 'Student', function($scope, $stateParams, Student) {
$scope.student = new Student();
$scope.student.loadStudent($stateParams.studentId);
}]);
这里loadStudent()从url中获取当前学生的id并设置学生属性。
学生详情视图:
<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>
我做错了什么?感谢任何帮助!
【问题讨论】:
-
在
$scope.student = new Student();之后,您是否在console.log$scope.student? -
@DMCISSOKHO - 是的,然后我看到类似 > {id: null, name: null} 但是当我点击对象展开时,我看到了正确的名称和属性。
-
如果你在
$scope.student.loadStudent($stateParams.studentId);之后使用console.log? -
@DMCISSOKHO - 结果完全一样。是
loadStudent()中的异步 get 调用吗? -
好的,你能把你的对象贴在这里吗?
标签: javascript angularjs angularjs-scope javascript-objects angularjs-http