我是 AngularJS 的初学者。我想知道哪种方法是解决我的问题的最佳方法。我有一个服务返回一个像这样的复杂 JSON 对象(更复杂!!!):
var complexObj = {
property1: 'p1',
property2: 'p2',
complexNested: {
nestedProperty1: 'np1',
nestedProperty2: 'np2'
},
arrayOfObjects: [{ arrP1: 'arrp1', arrP2: 'arrp2' }, { arrP1:'arrp3', arrP2: 'arrp4' }]
};
我想要:
- 页面加载时从服务检索 json 对象
- 将每个属性或嵌套对象绑定(bind)到正确的 Controller
- 用户通过 UI 修改值
- 收集所有修改的数据并重建复杂对象
- 将修改后的对象发送回服务进行更新和计算
之前我使用 Knockout.js 并通过序列化模型并使用映射插件轻松完成此任务。 AngularJS 中最好的方法是什么? 提前致谢。
法比奥
最佳答案
On page load retrieve the json object from the service
一旦 Controller 加载,页面的 Controller 就可以调用服务来检索复杂对象。
Bind each property or nested object to the correct controller
有很多方法可以做到这一点。获得对象后,您可以直接引用其属性并传递它的各个部分。
如果您使用父子 Controller ,子 Controller 可以修改存储在父 Controller 作用域中的复杂对象。
如果您使用指令,则可以根据需要通过隔离范围传递复杂对象的特定部分。
您还可以将复杂对象存储在服务(这是一个单例)中并在 Controller 之间共享。
User modify the values through UI
Collect all the modified data and rebuild the complex object
Angular 的 2 路数据绑定(bind)将处理这部分。使用 ngModel 指令保存您需要的任何输入。您所做的任何更改都应该反射(reflect)在“主”对象中。
Send the modified object back to service for update and calcultation
这将是再次调用您的服务的问题,该服务应该发出一个以该对象作为其主体的 PUT 请求。
您的 PageController 和服务可能如下所示:
页面 Controller
function PageController($scope, ComplexObjectService) {
loadComplexObject();
function loadComplexObject() {
ComplexObjectService.get().then(function(complexObject) {
$scope.complexObject = complexObject;
});
}
$scope.onSave = function(complexObject) {
ComplexObjectService.save(complexObject).then(function(result) {
//Do something.
});
}
}
angular
.module('ModuleName')
.controller('PageController', ['$scope', 'ComplexObjectService', PageController]);
复杂服务
function ComplexObjectService($http) {
this.get = function() {
return $http.get('/api/to/get/complex/object').then(function(response) {
return response.data;
});
};
this.save = function(complexObject) {
return $http.put('/api/to/save/complex/object', complexObject).then(function(response) {
return response.data;
});
};
}
angular
.module('ModuleName')
.service('ComplexObjectService', ['$http', ComplexObjectService]);
关于javascript - AngularJS 中与后端服务通信的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28065222/