Search code examples
angularjsmodel-view-controllerviewangular-ui-router

What's the purpose of adding the extra 'views:{'foo':{}}' when declaring a view in angular?


What's the purpose of declaring the a view with views:{} e.g.

.state('app.example', {
    url: "/example",
    views: {
      'my-example': {
        templateUrl: "views/example.html",
        controller: 'myCtrl'
      }
    }
  })

as opposed to this

 .state('app.example', {
        url: "/example"
        templateUrl: "views/example.html",
        controller: 'myCtrl'
        }
      })

Solution

  • Ok I figured it out and I created a codepen for this to get it to fit nicely inside other ionic app. This updates the child view when a button or a sidemenu item is pressed with more detail inside the codepen by making multiple child views share a name like so

         views: {
                'shared-child-view' :{
                  templateUrl: "[path to your children, in our case child1.html and child2.html]"
                }
              }`
    

    where it would look something like this

     .state('sidemenu.parent.child1', {
          url: "/child1",
          views: {
            'shared-child-view' :{
              templateUrl: "child1.html"
            }
          }
        })
           .state('sidemenu.parent.child2', {
          url: "/child2",
          views: {
       'shared-child-view': {
         templateUrl: "child2.html"
       }
     }
        })
    `
    

    Where it can sit in a parent that sits in an abstract state like this (but it doesnt have to but It's likely that this is how your ionic app will be setup):

    .state('sidemenu', {
      url: "/sidemenu",
      abstract: true,
      templateUrl: "sidemenu.html"
    })
    .state('sidemenu.parent', {
      url: "/parent",
      views: {
        'menuContent' :{
          templateUrl: "parent.html"
        }
      }
    })
    

    You can alternate or change each child view inside a view to evrey view with the same name, in this case "shared-child-state"

      <div ui-view name="shared-child-view"></div>
    

    and it can be made clickable with

    <a href="#/sidemenu/parent/child2" class="item">Child View 2
                  </a>
    

    This doesnt work if you use ui-serf.

    I hope this helps someone!