Search code examples
angularjsangularjs-ng-repeat

Call function in controller with $http.get


When i run this i get no value at all, just endless looping errors. (Error: [$rootScope:infdig])

My html:

{{getName(5)}}

This is my function:

$scope.getName = function(id) {
    $http.get('get.php?id='+id).then(function(response) {
        return response.data;
    });
}

When i call get.php?id=5 i get a normal answer like: "Jake Something"

When i call $scope.getName(5) in my controller i get the right value, no errors.

Is there a way to fix this or any other way to get the right values?


Solution

  • Fixed it by using directive:

    myApp.directive('getCustomer', function($http) {
        return {
            restrict : 'E',
            scope: {
                customerid: '='
            },
            template: "{{data}}",
            link: function(scope, elem, attr) {
                var url = 'get.php?id='+scope.customerid;
                $http.get(url).then(function(response) {
                    scope.data = response.data;
                });
            }
        };
    });
    

    in html:

    <get-customer customerid="5"></get-customer>
    

    Outputs:

    Jake Something