3

I am new to Angular Js. Recently I was doing work with routes and templateUrl. This was straight forward. But now I want to do something if that is even possible.

I want to show different view or template with same route but depending on the attribute of the data that I get from the Server. If the status is A then show the edit-mode and if the status is B then show the read-only mode. The data values are same except the status. I was doing ng-if in the template and toggle back and forth. It could be done this way but for the re-usability purpose I want to have a separate templates for each and call the template in the route depending on those attributes.

Let me know if that can be done. Thank you!

Rana_S
  • 1,520
  • 2
  • 23
  • 39

1 Answers1

3

There is a working example, which is close to this Q & A: Trying to Dynamically set a templateUrl in controller based on constant

In case I understand you properly, the way could be:

  • use $stateParams for switching read / edit
  • templateProvider to select template
  • $templateRequest to profit from angular native wrapper over $http + $tempalteCache

The state def would be very simple:

$stateProvider
    .state('myState', {
        url: '/myState/:operation',

        templateProvider: ['$stateParams', '$templateRequest',
          function($stateParams, $templateRequest) {

            var templateName = 'read.html';

            if ($stateParams.operation === "edit") {
                 templateName = 'edit.html';
            } 

            return $templateRequest(templateName);
        }],
        controller: function ($state) {
        }
    });

And links to this state:

  <a href="#/myState/read">
  <a href="#/myState/edit">

Check the examle in action here

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335