Search code examples
angularjsangular-ui-routerangularjs-componentsangularjs-1.5

How to use angular 1.5 components with ui-router states


Right now, angular ui-router project didn't have anything explicit about angular 1.5 components. My project requirement is to use nested states and I want to use angular 1.5 components to easily migrate to angular 2. I'm looking for a best boilerplate of both. Options 1,2 & 4 from the below link are supported. I want to know what is the optimal option for nested states and for migration to angular 2.

Angular 1.5 components with nested states


Solution

  • I just shared this solution with a buddy. Not sure if it fits your exact requirements but with UI-Router 1.0.0 you can route directly to a component. To take this a step further, with nested states, we can specify a specific component on a named view. We then link to our child state in the markup using ui-sref. When this state becomes active, so does its view's component.

    If you want to make these views dynamic, say based on a user role, then you could use a templateProvider function. However, with templateProvider you can't use a component to define a view so you may have to just return the component's tag.

    e.g. <editAdminProfileForm></editAdminProfileForm>

    For more on conditional views with templateProvider see my other answer here: Angularjs ui-router : conditional nested name views

    And here's some additional reading on UI-Router with components:
    https://ui-router.github.io/guide/ng1/route-to-component
    https://ui-router.github.io/docs/latest/interfaces/ng1.ng1statedeclaration.html#component

    app.js

    ...
    
    .state('app', {
      abstract: true,
      templateUrl: 'templates/user-profile.html',
    })
    
    .state('app.profile', {
      url: '/profile',
      views: {
        'profile': {
          component: 'userProfile'
        }
      }
    
    })
    
    .state('app.profileEdit', {
      views: {
        'editProfile': {
          component: 'editProfileForm'
        }
      }
    });
    

    user-profile.html

    <ui-view>
      <div ui-view="profile"></div>
      <div ui-view="editProfile"></div>
    </ui-view>
    

    user-profile-component.js
    profile-edit-component.js

    yourApp.component('userProfile', { ... });
    
    yourApp.component('editProfileForm', { ... });
    

    user-profile-component.html

    <button type="button" ui-sref="app.profileEdit()">Edit Profile</button>