user3807481
user3807481

Reputation: 3

What is the best way to organize code using AngularJS?

I am creating an app, and there is used ui router, all html data append to this tag:

 <div class="app" ui-view >

But I'd like to include header and footer to my app, and my question is - is it better to use smth like this in index.html:

<div ng-controller="top" header></div>
  <div class="app" ui-view >
<div ng-controller="bottom" footer></div>

or I should include in every html page two directives - header & footer.

Upvotes: 0

Views: 67

Answers (2)

cbass
cbass

Reputation: 2558

What I usually to is to use an abstract state for the layout which all other states inherits.

$stateProvider
    .state('e', {
        abstract: true,
        controller: 'WhateverController',
        templateUrl: 'layout.html',
    })
    .state('e.home', {
        url: '/',
        templateUrl: 'home.html'
    })

Your layout would look something like this:

`<div class="header">
     Some content
</div>
<div ui-view></div>
<div class="footer">
   Footer Content
</div>`

Upvotes: 0

Jeff N
Jeff N

Reputation: 440

Why not have each of those things be custom element directives, with their own controllers? That way, you could set it up like this:

<ui-header></ui-header>
<ui-view></ui-view>
<ui-footer></ui-footer>

This is the "AngularJS way" to do it. It makes the HTML more readable, and also much more concise. Each of those directives will have a template either as a string or in a file that is pointed to during directive creation. That looks something like this:

app.directive('uiHeader', function() {
  return {
    restrict: 'E',
    templateUrl: '/path/to/template.html',
  };
});

The above will place the contents of your template file in the place where you put <ui-header></ui-header>. It is also possible to define a controller for each directive, as well as allowing each to have its own scope. You can read more about the creation of custom directives here.

Upvotes: 1

Related Questions