Search code examples
javascriptangularjsmean-stackangular-ui-grid

$scope.uiGrid is undefined


I'm trying to create a table using angularjs ui-grid but I keep getting told that $scope.uiGrid is undefined, can anyone tell me what I'm doing wrong?

    requestYelp.success(
    function(obj) 
    {
        console.log(obj.businesses[0].name);

        $scope.gridOptions = {
            enableSorting: true,
            rowHeight:100,
            columnDefs: [
            { field: 'name' },
            { field: 'company'  },
            { field: 'image', cellTemplate:"<img width=\"50px\" ng-src=\"{{grid.getCellValue(row, col)}}\" lazy-src>"}
            ],

            data:[
            {name:obj.businesses[0].name,company: "Company1", image: obj.businesses[0].image_url},
            {name:obj.businesses[1].name,company:"Company2",image:obj.businesses[1].image_url},
            {name:obj.businesses[2].name,company:"Company3",image:obj.businesses[2].image_url}
            ]
        };
    }
);
}]);

console.log(obj.businesses[0].name) will put the right data to the console so it's not a problem with the obj variable. The code only breaks when it gets to gridOptions.


Solution

  • I don't know the exact details how the ui-grid works. But I'm guessing that the ui-grid directive immediately expects $scope.gridOptions to be available on the $scope. However, you are assigning $scope.gridOptions only after the asynchronous http request has finished loading.

    You should try to provide an empty (or adequately primed) $scope.gridOptions immediately before doing the http request.

    Alternatively there's a trick to delay linking of any directive by adding an additional ng-if on the same element. Set it up something like this:

    ng-if='whenHttpRequestHasFinishedLoading'

    And inside the success() function just set $scope.whenHttpRequestHasFinishedLoading = true