1

I have bunch of JSON models in my project and I need to show different models depends on user's actions.

Here is Angular router code:

app.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/home.html',
        controller: 'HomeCtrl'
      }).when('/doc/:section, {
        templateUrl: 'views/doc.html',
        controller: 'DocCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  }]);

And here is DocCtrl.js file:

app.controller('DocCtrl', ['$scope', '$http', 'JSONModelsService',
    function ($scope, $http, JSONModelsService) {

        var formData = {};

        $scope.group = {};
        $scope.sections = [];

        JSONModelsService.get([section])
            .then(function (response) {
                console.log(response);
                $scope.group = response.data.groups[0];

                $scope.sections = $scope.group.sections;
            });

    }]);

I basically need to make section dynamic so I can show different models in my views. However, I'm confused how I can do it. I just have a folder called JSONModels with multiple json files.

1 Answer 1

1

If I understand your question correctly, you are aiming at replacing the [section] part of your code with an actual section identifier?

When a user visits your /doc/:section route, e.g. /doc/my-doc you can access the :section part by injecting the $routeParams service into your controller.

app.controller('DocCtrl', ['$scope', '$http', '$routeParams', 'JSONModelsService',
    function ($scope, $http, $routeParams, JSONModelsService) {
  ...

Using the $routeParams service, you have access to your route parameters. So you can simple access the :section parameter, by reading it off $routeParams.section.

A full example (of what I think you're trying to achieve):

app.controller('DocCtrl', ['$scope', '$http', '$routeParams', 'JSONModelsService',
function ($scope, $http, $routeParams, JSONModelsService) {

    var formData = {};

    $scope.group = {};
    $scope.sections = [];

    JSONModelsService.get([$routeParams.section])
        .then(function (response) {
            console.log(response);
            $scope.group = response.data.groups[0];

            $scope.sections = $scope.group.sections;
        });

}]);

If you would like to know more, take a look at step 7 of the angular tutorial: https://docs.angularjs.org/tutorial/step_07

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

Comments

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.