User146378 User146378 - 1 month ago 7
AngularJS Question

Function not working in Angular

The below defined function will open a dialog from a loop

$http.post(url,req, "")
.then(function (response) {
for (var r = 0; r < response.data.items.length ; r++){
foo(response.data.items[r], r);
}

function foo(i, j) {
$rootScope.dialogOpen = function () {
alert('i = ' + i + ', j = ' + j );
}
}


While debugging I am able to hit the function but the dialog isn't opening . What went wrong .

Answer

Looks to me like $rootScope.dialogOpen() gets defined but never called. The body of your function foo declares $rootScope.dialogOpen() but this is never called.

I am not sure how your app is structured, but it's almost certain you shouldn't be defining $rootScope.dialogOpen() inside of foo. The dialogOpen function should be declared elsewhere such as in your master controller and called by foo, i.e.:

// In your master controller:
$scope.dialogOpen = function(i,j)
{
    $scope.num= i;
    $scope.count = j;
};

// In the controller that contains your $http.Post():
function foo(i,j)
{
    $rootScope.dialogOpen(i,j);
}
$http.post(url,req, "").then(function (response) {
     for (var r = 0; r < response.data.items.length; r++){
         foo(response.data.items[r], r);
     }
});
Comments