0

我是 AngularJS 的新手,并尝试制作一个 MVC 应用程序,其中控制器可以连接到相同类型的多个模型。

所以:

我创建了一个连接到测试模型的控制器以获取异步信息,例如:

function TestController($scope, Test)
{
    $scope.model = {};  

    $scope.load : function(id) {
         Test.get($scope, id);
    }
}

该模型使用 http 协议从服务器检索 (json) 信息。模型看起来像:

myApp.factory('Test',function($http) {
    get : function(variable, id) {
        $http({
           url: 'api/load/'+id
        }).success(function(response) {
           variable.model = response;       
        });
     } 
});

在那里,名称“模型”被硬连接到控制器中。所以没有办法在控制器中加载第二个测试模型,因为现有的模型会被覆盖。

如果我换行:

    Test.get($scope, id);

    Test.get($scope.model, id);

和模型

     variable = response;

Angular 停止的魔力。模型未在控制器中更新。Javascript 中没有 byRef。

是否有一种解决方法,以便模型可以在一个控制器中多次使用?

4

1 回答 1

2

好吧,您不需要像这样调用服务。首先,$http 调用返回可以通过使用 'then' 回调处理的承诺。因此,您可以为类似的调用添加多个不同的回调。在你的情况下:

myApp.factory('Test',function($http) {
    get : function(id) {
        return $http({
            url: 'api/load/'+id
        });
    } 
});

在你的控制器中:

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;
        });
    } 
});

在你的控制器中:

function TestController($scope, Test) {
    $scope.model = {};  

    $scope.load : function(id) {
        Test.get($scope, 'var1', id);
        Test.get($scope, 'var2', id);
    }
}
于 2014-03-29T19:24:27.580 回答