Question

I new to AngularJS and try to make a MVC application where the Controller can connect to multiple Models of the same type.

So:

I create a controller that connects to the Test model to get the information async like:

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

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

The model uses the http protocol to retrieve the (json) information from the server. The model looks like:

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

There the name 'model' is hard-wired into the controller. So there is no way of loading a second Test model, in the controller, because the existing would be over written.

If I change the line:

    Test.get($scope, id);

to

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

And the model to

     variable = response;

The magic of Angular stop. The model isn't update in the controller. There is no byRef in Javascript.

Is there a workaround so the Model can be used multiple time in one Controller?

Was it helpful?

Solution

Well, you don't need to call the service like this. First of all, $http calls return promises which can be handled by using 'then' callbacks. So you can add multiple different callbacks for the similar calls. In your case:

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

And in your 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;
        });
    }
}

Another way is to do like this:

myApp.factory('Test',function($http) {
    get : function(context, variable, id) {
        return $http({
            url: 'api/load/'+id
        }).success(function(result) {
            context[variable] = result;
        });
    } 
});

And in your controller:

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

    $scope.load : function(id) {
        Test.get($scope, 'var1', id);
        Test.get($scope, 'var2', id);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top