1

I am exploring Angular.js UI-Grid. However, I can't seem to figure out why data is coming as undefined when I am making an HTTP request in my service. It seems to work fine when I make an HTTP request from my controller. How can I make Ui-Grid work in a modular way?

HTML

<div id="grid1" ui-grid="gridOptions" class="grid"></div>

Controller

app.controller('tableCtrl', function($scope, tableService) {

    var getAllArtistData = function() {

        tableService.getArtistData().then(function(data) {
            console.log("this is controller data", data);
            $scope.gridOptions.data = data;

            $scope.gridOptions = {};

            $scope.gridOptions.columnDefs = [
                {name:'artist_id'},
                {name:'first_name'}
            ];

            });
        };
    getAllArtistData();
});

Service

app.service('tableService', function($http, $q) {

    /************************************************
    GET ARTIST DATA 
    ************************************************/
    this.getArtistData = function() {

        var defer = $q.defer();

        $http.get('../../../data/artists-lite.json')
            .success(function(response) {
                console.log("this is response", response);
                defer.resolve(response);
            })
            .error(function(err) {
                defer.reject(err);
            });

        return defer.promise;

    };
});

App.js

'use strict';

var app = angular.module('bucketfeet', ['ui.router','ui.grid', 'ngAnimate']);

app.run(function($state, $rootScope) {
    $rootScope.$state = $state;
});

app.config(function($stateProvider, $urlRouterProvider) {

    $urlRouterProvider
    .otherwise('/');

    $stateProvider
    .state('stats', 
        {
            url: '/stats',
            templateUrl: './js/views/statsTmpl.html'
        })
    .state('table', 
        {
            url: '/table',
            templateUrl: './js/views/tableTmpl.html',
            controller: 'tableCtrl'
        });

});
2
  • $scope.gridOptions1 is undefined Commented Oct 5, 2015 at 4:15
  • Here is the working pen of your code codepen.io/anon/pen/dYvEym. The initial reasons for your problem may be you are missing proper version of ui-grid or its dependancy. Have a look at all files in code pen. Commented Oct 5, 2015 at 5:36

1 Answer 1

6

In your controller you should initialize your gridOptions before using it. Even better, try extracting setting up of this variable to controller scope, leave filling only the data in asynchronous method:

app.controller('tableCtrl', function($scope, tableService) {

    // Initialize gridOptions with all the properties, except for data
    $scope.gridOptions = {};
    $scope.gridOptions.columnDefs = [
        {name:'artist_id'},
        {name:'first_name'}
    ];
    $scope.gridOptions.data = [];

    var getAllArtistData = function() {

        tableService.getArtistData().then(function(data) {
            console.log("this is controller data", data);

            // fill only data in asynchronous callback
            $scope.gridOptions.data = data;
        });
    };
    getAllArtistData();
});

Method tableService.getArtistData() is executed asynchronously and the callback for this method is only executed when the data is retrieved from server. This can happen in couple of milliseconds, it can happen in minutes. The rendering of the grid needs to happen before the callback is executed, and it lacks the metadata information of how to render the grid. That is why I suggest initializing grid metadata before launching the asynchronous call, and inside the callback setting only the data.

Sign up to request clarification or add additional context in comments.

5 Comments

@MihirPatel Do you get the exception first, or do you get this is controller data logged to console first?
I get this is controller data logged to my console. My error is on "$scope.gridOptions.data = data;" here. I just don't know what I am doing wrong.
@MihirPatel There is no code $scope.gridOptions.data = data in your question, can you update the question with the latest code that you are using?
@dotnetom, I have the same issue and I get the undefined data before log in the console. My gridOption instance is not attached to the scope but to this. Here is the code likn pastebin.com/FJgmDJKf
this solved it for me, the object was being accessed in code before it was rendered in html. Adding the first line of the two here solved it for me: $scope.gridOptions = {}; $scope.gridOptions.data = []; make sure that the gridOptions were a "thing" first, don't assume that just because it exists in the html that it is ready to be accessed in code i guess

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.