我是 AngularJS 的新手,并尝试制作一个 MVC 应用程序,其中 Controller 可以连接到同一类型的多个模型。
所以:
我创建一个连接到测试模型的 Controller 以获取异步信息,例如:
function TestController($scope, Test)
{
$scope.model = {};
$scope.load : function(id) {
Test.get($scope, id);
}
}
模型使用http协议(protocol)从服务器检索(json)信息。该模型如下所示:
myApp.factory('Test',function($http) {
get : function(variable, id) {
$http({
url: 'api/load/'+id
}).success(function(response) {
variable.model = response;
});
}
});
名称“模型”被硬连接到 Controller 中。所以没有办法加载 在 Controller 中的第二个测试模型,因为现有的将被覆盖。
如果我改变线路:
Test.get($scope, id);
至
Test.get($scope.model, id);
模型为
variable = response;
Angular stop 的魔力。 Controller 中的模型未更新。没有 byRef 在 JavaScript 中。
是否有解决方法,使模型可以在一个 Controller 中多次使用?
最佳答案
好吧,您不需要像这样调用服务。首先,$http 调用返回 promise ,可以使用“then”回调来处理它。因此您可以为类似的调用添加多个不同的回调。对于您的情况:
myApp.factory('Test',function($http) {
get : function(id) {
return $http({
url: 'api/load/'+id
});
}
});
在你的 Controller 中:
function TestController($scope, Test) {
$scope.model = {};
$scope.load : function(id) {
Test.get(id).then(function(result) {
$scope.var1 = result;
});
Test.get(id).then(function(result) {
$scope.var2 = result;
});
}
}
另一种方法是这样做:
myApp.factory('Test',function($http) {
get : function(context, variable, id) {
return $http({
url: 'api/load/'+id
}).success(function(result) {
context[variable] = result;
});
}
});
在你的 Controller 中:
function TestController($scope, Test) {
$scope.model = {};
$scope.load : function(id) {
Test.get($scope, 'var1', id);
Test.get($scope, 'var2', id);
}
}
关于javascript - 如何在AngularJS中将数据从模型异步返回到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22735570/