我有一个与 Web API 后端对话的 angularjs 前端。我是这个框架的新手,不确定如何将复杂的数据从 Web api 提取到我的应用程序 $scope 中。然后我将使用this front end library在日历小部件中显示数据。
我有一个 Session 表和一个 Session_Instance 表,它们以一对多关系链接在一起。我可以使用 $http 获取数据,然后将其作为对象存储在 $scope 中。问题是我想在这个对象上定义方法并将代码从 Controller 中取出,以便我可以利用 Angular 的 DI,但我不知道应该使用什么或如何在 Angular 中执行此操作。
是否可以在 Angular 中建立复杂的数据模型,并使用提供程序使其在应用程序中保持最新状态?
最佳答案
如果我正确理解您的问题,执行此操作的正确 Angular 方法是将您的数据包装为服务。
举个例子,这里有一些从 this blog 复制的代码:
(function () {
var person = angular.module("person");
person.factory("PersonService", [
'$http',
'httpRestValue',
function ($http, httpRestValue) {
var PersonService = {
data: {
currentPerson: {},
persons : []
},
getPerson: function (id) {
return $http.get(httpRestValue + "person/"+id)
.success(function success(data) {
PersonService.data.currentPerson = data;
})
.error(function error() {
});
},
getPersons : function(){
return $http.get(httpRestValue + "person/list")
.success(function success(data) {
PersonService.data.persons = data;
})
.error(function error() {
});
},
savePerson : function(person){
return $http.post(httpRestValue + "person/",person)
.success(function success() {
PersonService.getPersons();
})
.error(function error() {
});
},
deletePerson : function(id){
return $http.delete(httpRestValue + "person/"+id)
.success(function success() {
PersonService.getPersons();
})
.error(function error() {
});
}
};
return PersonService;
}
]);
})();
关于javascript - AngularJS 提供者和模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25537586/