简体   繁体   中英

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.

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 .

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>`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM