gpt4 book ai didi

angularjs - 在 AngularJS 中创建自定义对象

转载 作者:行者123 更新时间:2023-12-04 03:20:17 26 4
gpt4 key购买 nike

我想在 AngularJS 中实现我自己的自定义对象/类。但是,我一直坚持使用工厂/服务作为自定义对象的概念——我知道工厂和服务是用来提供应用程序的业务逻辑的,但是我可以在一个应用程序中创建多个工厂和服务吗?如果是这样,术语“单例”(我读过的许多文章都将服务描述为)究竟意味着什么?

例如,这是否是在 AngularJS 中创建一个填充有学生对象的基本学校对象的有效和/或首选方法?

app.factory('schoolService',function(student){
var school = {};
school.students = [];
school.addStudent = function(){
var newStudent = new student();
this.students.push(newStudent);
}
return school;
}
app.service('student',function(){
//anyway to toss in a constructor here?
this.name = 'name';
this.getName = function(){
return this.name;
}
}
app.controller('schoolCtrl',function(schoolService){
schoolService.addStudent(); //obviously normally wouldn't do this, but for demonstration purposes
$scope.students = schoolService.students;
//expect $scope.students to equal an array of length 1, with one student object
}

提前致谢,对于所有嵌套的问题深表歉意!

最佳答案

单例保持静态。 Controller 在调用时加载。您可以将学生存储在服务中,因为它将在您的应用程序的整个生命周期中持续存在,并且可以在 Controller 之间共享。

https://jsfiddle.net/jtgd6tjn/

有 Angular 的

function AppCtrl($scope, SchoolService) {
$scope.students = SchoolService.students;
$scope.addStudent = function() {
SchoolService.students.push($scope.newStudent);
$scope.newStudent = {};
}
}

function SchoolService() {
var service = {
students: []
};
return service;
}

HTML

<div ng-app="myApp" ng-controller="AppCtrl">
<form ng-submit="addStudent()">
<input type="text" ng-model="newStudent.first">
<br>
<input type="text" ng-model="newStudent.last">
<br>
<button type="submit">
Add New Student
</button>
</form>
<hr>
<ul>
<li ng-repeat="student in students"> {{ student.first}} {{ student.last }} </li>
</ul>
</div>

关于angularjs - 在 AngularJS 中创建自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38853251/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com