Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Multi-Page App Site Boilerplate Site Structure Advice

I am looking for some guidance with creating an AngularJs multi-page app served by a Laravel Backend. All web app tutorials on the net point to creating SPAs and I am just getting started with Angular - so please go easy on me.

ProductPage example - http://example.com/products/widget

<html data-ng-app='ExampleApp'>
    <head>
    </head>
    <body data-ng-controller='ProductController'>
        // ProductPage Content Served by laravel with angular tags

        <script type="text/javascript" src="/js/lib/angular.min.js"></script>
        <script type="text/javascript" src="/js/app.js"></script>
        <script type="text/javascript" src="/js/controllers/ProductController.js"></script>
    </body>
</html>

CartPage Example - http://example.com/cart

<html>
    <head>
    </head>
    <body data-ng-controller='CartController'>
        // CartPage Content Served by web-server with angular tags

        <script type="text/javascript" src="/js/lib/angular.min.js"></script>
        <script type="text/javascript" src="/js/app.js"></script>
        <script type="text/javascript" src="/js/controllers/CartController.js"></script>
    </body>
</html>

So in the above examples, I have created two pages, which are served by the web server with pretty much all static content. But the pages have been marked up with angular tags. On each static page, I have referenced a different AngularJS controller.

Is this the right way of tackling the problem or should I be allowing app.js to load up the controllers / inject the dependencies?

Also, any guidance on sharing data between controllers in this multi-page app and links to decent resources / examples would be really helpful. e.g Would I need to pass e.g. Items added to shopping cart to an api from the product page, then query this api again to retrieve the cart contents?

like image 235
Gravy Avatar asked Mar 21 '14 10:03

Gravy


1 Answers

You should include the ngRoute module and let AngularJS load the controllers for you. Please refer to AngularJS docs to find out how to work with routings.

As for sharing data between controllers, services are what you're looking for. Creating a service is as easy as this:

app.factory("ServiceName", [function() {
    return {
        somevar: "foo"
    };
}]);

Then, in your controllers, you inject the service like this:

app.controller("ContactCtrl", ["$scope", "ServiceName", function($scope, svc) {
    $scope.somevar = svc.somevar;
}]);

The service's state is retained for as long as you don't cause a physical page reload (which is why you should use ngRoute to load your controllers).

like image 175
mingos Avatar answered Nov 13 '22 13:11

mingos