Matieu
Matieu

Reputation: 39

Construct URL depending on user choice AngularJS

I'm building a website that basically shows specific data from JSON files in a table.

My issue is that I'll have over 250 potential different JSON files that could be loaded depending on the user choice. For example, if the user clicks on the button "a" and then the button "b" it will need to load the file "a_b.json". For now I've tested with one json file, here is my test code:

var app = angular.module('webStatistics', ['ngRoute']);
app.config(function($routeProvider){
    $routeProvider
        .when('/stats/views/', {templateUrl: 'home'})
        .when('/stats/views/home.html', {
            controller : 'testController'
            templateUrl: '/stats/views/home.html'
        })
        .otherwise({redirectTo : '/'});
});
app.controller('testController', function($scope, $http) {
      $http.get('../app/sources/stats/004/a_b.json').success(function(data) {
        $scope.variables = data;
      });
});

I would like to know if there is a way to "dynamically construct" the URL that I give to my $http service? So if user's choice is x and option z ->../stats/x/x_z.json

Only one file will be loaded at a time.

Upvotes: 0

Views: 30

Answers (1)

Huy Chau
Huy Chau

Reputation: 2240

Hope this help.

var app = angular.module('webStatistics', ['ngRoute']);
app.config(function($routeProvider){
    $routeProvider
        .when('/stats/views/', {templateUrl: 'home'})
        .when('/stats/views/home.html', {
            controller : 'testController'
            templateUrl: '/stats/views/home.html'
        })
        .otherwise({redirectTo : '/'});
});
app.controller('testController', function($scope, $http) {
    $scope.item1 = '';
    $scope.item2 = '';

    $scope.getData() {

        if ($scope.item1 && $scope.item2) {
            var api = '../app/sources/stats/004/' + item1 + '_' + item2 + '.json';
            $http.get(api).success(function(data) {
                $scope.variables = data;
            });
        }

    };
});

Upvotes: 1

Related Questions