Search code examples
jsonangularjsmodel-view

view not gathering data from service through controller


Having trouble loading an external json file and having it's contents display on my view. I've included my view, controller and services code. What do I need to change?

view.html

<div ng-controller='BaseCtrl'>
    <table class="table table-hover">
        <tbody>
           <tr class="tr-sep" ng-repeat="example in examples" ng-click="showUser(example)">
              <td>{{example.name}}</td>
              <td>{{example.type}}</td>
              <td>{{example.size}}</td>
           </tr>
        </tbody>
    </table>
</div>

controller.js

'use strict';

angular.module('projyApp')
  .controller('BaseCtrl', function ($scope, data) {
    $scope.examples = data.getAllExamples();

    $scope.showUser = function(example) {
        window.location = '#/user/' +example.size;
    };

  });

service.js

'use strict';

angular.module('projyApp')
  .service('data', function data() {
        var examples;

        var getAllExamples = function () {

            $http.get("../../TestData/Examples.json").success($scope.examples = data.examples);
        };

  });

Solution

  • Your service code isn't correct. I see the following problems:

    • You're creating a local variable getAllExamples that's not accessible from outside the service;
    • You're using the $http service, but that dependency isn't expressed in the service constructor;
    • You're trying to update the scope from the service, but it's inaccessible from there. Plus, the $scope variable is not even defined inside the service code.

    Here's how your service could look like:

    .service('data', function($http) {
        this.getAllExamples = function(callback) {
            $http.get("../../TestData/Examples.json")
                .success(function(data) {
                    if (callback) callback(data.examples);
                });
            };
    });
    

    And your controller code would be like this:

    .controller('BaseCtrl', function ($scope, data) {
        data.getAllExamples(function(examples) {
            $scope.examples = examples;
        });
    
        $scope.showUser = function(example) {
            window.location = '#/user/' +example.size;
        };
    });
    

    You could ditch the callback in the getAllExamples function and work directly with the $http.getreturned promise, but that's a bit more complicated.

    Update Added a Plunker script to illustrate the code above.