简体   繁体   中英

Single Page Apps with AngularJS - How to model?

I built a single page app based on this tutorial:

https://scotch.io/tutorials/single-page-apps-with-angularjs-routing-and-templating

this is the file structure that they suggested:

 - script.js             <!-- stores all our angular code -->
    - index.html            <!-- main layout -->
    - pages                 <!-- the pages that will be injected into the main layout -->
    ----- home.html
    ----- about.html
    ----- contact.html

the part about the html pages is pretty straightforward - a page to every ng-view. cool...

but the script.js seems to me like a bad modeling.

should I really put all my js code in one file?

it seems to me like this isn't the best way to model it.

what happened if I will have a lot of pages in my single page app?

I will have a long long one js file with all the controllers..

what is the best practice to model a single page app in angularjs?

Thanks!

// script.js

    // create the module and name it scotchApp
        // also include ngRoute for all our routing needs
    var scotchApp = angular.module('scotchApp', ['ngRoute']);

    // configure our routes
    scotchApp.config(function($routeProvider) {
        $routeProvider

            // route for the home page
            .when('/', {
                templateUrl : 'pages/home.html',
                controller  : 'mainController'
            })

            // route for the about page
            .when('/about', {
                templateUrl : 'pages/about.html',
                controller  : 'aboutController'
            })

            // route for the contact page
            .when('/contact', {
                templateUrl : 'pages/contact.html',
                controller  : 'contactController'
            });
    });

    // create the controller and inject Angular's $scope
    scotchApp.controller('mainController', function($scope) {
        // create a message to display in our view
        $scope.message = 'Everyone come and see how good I look!';
    });

    scotchApp.controller('aboutController', function($scope) {
        $scope.message = 'Look! I am an about page.';
    });

    scotchApp.controller('contactController', function($scope) {
        $scope.message = 'Contact us! JK. This is just a demo.';
    });

This exhaustive styleguide recommends creating folders and organzing your app based on features. https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#application-structure

I recommend reading the whole "Application Structure" section, which really helped me organizing my angular projects

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