Skip to content
Brice Leroy edited this page Apr 24, 2015 · 1 revision

The index jade

An example of index heavily leveraging view segmentation from ui-router

doctype html
html
  head
    title Foo

  body(ng-app='app')
    div(ui-view="navbar")
    div(ui-view="content")
    div(ui-view="sub-content")
    div(ui-view="footer")
    div(ui-view="modal")

The ui-state the modal helpers

This might very well not be necessary at all. We could simply fill-up the modal ui-view section and leverage native angular $animate to make it pretty.

'use strict'

angular.module('app')
  .config [
    '$stateProvider'
    '$urlRouterProvider'
    (
      $stateProvider
      $urlRouterProvider
    ) ->

      ###
      Modal state helper funtions
      They need to be attached to the `onExit` and `onEnter`
      to any modal state
      ###
      onModalExit = -> $('#root_modal').modal 'hide'
      onModalEnter = ($state, $rootScope) ->
        # Wrapper around go to parent state call
        # to keep a reference so we can detach the
        # hide event
        gotToParent = -> $state.go '^'

        # If the state change from the controller, we don't want
        # the default `goToParent` behavior to persist
        $rootScope.$on '$stateChangeStart', ->
          $('#root_modal').off 'hide.bs.modal', gotToParent

        # Let show the modal
        $('#root_modal').modal 'show'

        # If we close the modal we go to the parent state
        $('#root_modal').on 'hide.bs.modal', gotToParent

Defining the modal state

      $stateProvider.state 'ad',
        inherit: true
        parent: 'root-state'
        abstract: true

      $stateProvider.state 'ad.list',
        inherit: true
        url: '/list'
        views:
          '@':
            templateUrl: '/views/ad_list.html'
            controller: 'AdListCtrl'

      $stateProvider.state 'ad.list.edit_modal',
        onExit: onModalExit
        onEnter: onModalEnter
        url: '/{ad_id:int}'
        views:
          'modal@':
            templateUrl: '/ad/edit_modal.html'
            controller: 'AdEditCtrl' # doesn't have to be a modal controller
        resolver:
          'ad': (
            $stateParams
            adStore
          ) ->
            id = $stateParams.ad_id
            return adStore.get {id}

Modal controls

in the controller, leaving the modal state can be done by calling the parent state in the modal controller

angular.module('app')
  .controller 'AdEditCtrl', [
    '$state'
    'ad'
    'adStore'
    (
      $state
      ad
      adStore
    ) ->
      
      #... plenty of smart code here
      
      $scope.onSave = ->
        adStore.save(ad)
          .then ->
            $state.go '^'

To trigger the modal from the controller:

$state.go 'ad.list.edit_modal', {ad_id: ad.id}

To trigger it from the template

ul
  li(ng-repeat="ad in ads")
    a(
      ui-sref="ad.list.edit_modal({ad_id: ad.id})"
    ) Edit ad {{ ad.id }}
Clone this wiki locally