AngularJS-WebApi-EF icon indicating copy to clipboard operation
AngularJS-WebApi-EF copied to clipboard

Variable out of scope

Open sp00ky opened this issue 11 years ago • 0 comments

In crud-grid-directive.js, I was having a really hard time getting my lookups to work. It seems that c is getting out of scope in the loop in $scope.setLookupData. I kept getting errors because c.lookup was undefined. I tried putting everything in the loop in a closure like so:

            $scope.setLookupData = function () {
                for (var i = 0; i < $scope.columns.length; i++) {
                    (function (i) {
                        var c = $scope.columns[i];
                        if (c.lookup && !$scope.hasLookupData(c.lookup.table)) {
                            var res = crudGridDataFactory(c.lookup.table).query();
                            res.$promise
                                .then(function (data) {
                                    $scope.setIndividualLookupData(c.lookup.table, data); // c out of scope here?
                                })
                                .catch(function (data) {
                                    console.log("Error: ", data);
                                });
                        }
                    })(i);
                }
            };

Now it works perfectly. There are some other changes to how the promise is used that you may ignore or include at your discretion - I ended up making them while trying to debug the problem and thought they were good enough to keep in.

The closure idea came from StackOverflow:

http://stackoverflow.com/questions/17244614/promise-in-a-loop

Hope this is useful.

-k

sp00ky avatar Feb 10 '14 13:02 sp00ky