ui-router dynamic template path

前端 未结 3 1412
轻奢々
轻奢々 2020-12-01 08:01

I\'m using ui-router 0.2.8. I\'m wanting to load a template based on device width. I can get the device width without issue, set it in the scope etc but I can figure out how

3条回答
  •  抹茶落季
    2020-12-01 08:57

    This reference here was great for me figuring out how to do dynamic templates in angular, but I'd like to update with my own solution.

    • Solution 1 based on Dipesh Kc's (this works great for redefining parent templateUrl for abstract states) Notice I used toParams instead of $stateParams:

      // custom parent template
      .state('template', {
          abstract: true,
          url: "/tm/:tmfolder/:tmview",
          templateUrl: function (toParams) {
              return 'views/' + toParams.tmfolder + '/' + toParams.tmview + '.html';
          },
      })
      .state('template.contacts', {
          url: "/contacts/:folder/:view",
          templateUrl: function (toParams) {
              return 'views/' + toParams.older + '/' + toParams.view + '.html';
          },
      })
      
    • Solution 2 based on biofractal's (there is no way to update a parent templateUrl using this method):

      .state('contact', {
          url: "/contact/:folder/:view"
      })
      
      $rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
          var customStates = ["contact"]
          for (var i = 0; i < customStates.length; i++) {
              if (toState.name.indexOf(customStates[i]) != -1) {
                  toState.templateUrl = 'views/' + toParams.folder + '/' + toParams.view + '.html';
                  break;
              }
          }
      });
      

提交回复
热议问题