Routing In Multi Page Application in AngularJS-1.6.4

110 views
Skip to first unread message

abhishek srivastava

unread,
Nov 21, 2017, 2:31:56 AM11/21/17
to Angular and AngularJS discussion

I am developing a website in AngularJS-1.6.4 for product advertisement and It is the multi-page website. This website has two webpage index.html and product.html. The functionality of this project is -

On load of index.html, product list will be fetched from the database and show this product list in index.html. Each product Will be the link and on click on this product, a request will go to the server for getting this product details and show this product details in product.html page.


index.html is -


<head>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>

<script src="js/script.js"></script>

   
</head>

   
<body ng-controller="productController">

   
<div data-ng-init="onloadFun()">

           
<div>

           
<!--

            <div id="product" ng-repeat="product in products">




                <table>

                    <tr>

                        <td>

                            <a target="_blank" href={{product.product_Url}}>

                                <img src="{{product.product_Url}}" style="width:150px">

                            </a>

                        </td>

                    </tr>

                </table>

                -->


               
<table style="width:100%">

                   
<tr ng-repeat="product in products" ng-switch on="$index % 3">

                     
<td ng-switch-when="0">




                       
<a target="_blank" href={{products[$index].product_Url}}>

                               
<img src="{{products[$index].product_Url}}" style="width:150px">

                       
</a>

                       
<a style="cursor: pointer; margin-top: 5px;" ng-click="getProductById(products[$index].product_Url)">View Product Details and Buy Options</a>

                     
</td>

                     
<td ng-switch-when="0">

                       
<span ng-show="products[$index+1]">




                         
<a target="_blank" href={{products[$index+1].product_Url}}>

                               
<img src="{{products[$index+1].product_Url}}" style="width:150px">

                         
</a>

                         
<a style="cursor: pointer; margin-top: 5px;" ng-click="getProductById(products[$index+1].product_Url)">View Product Details and Buy Options</a>

                       
</span>

                     
</td>

                     
<td ng-switch-when="0">

                       
<span ng-show="products[$index+2]">    

                         
<a target="_blank" href={{products[$index+2].product_Url}}>

                               
<img src="{{products[$index+2].product_Url}}" style="width:150px">

                         
</a>

                         
<a style="cursor: pointer; margin-top: 5px;" ng-click="getProductById(products[$index+2].product_Url)">View Product Details and Buy Options</a>

                       
</span>

                     
</td>

                   
</tr>

               
</table>

           
</div>

       
</div>

   
</body>


          script.js is -


// create the module and name it
var gelovenIndia = angular.module('apparel', ['ui.router']);


app
.config(['$httpProvider', '$stateProvider', '$urlRouterProvider', function($httpProvider, $stateProvider, $urlRouterProvider) {


    $stateProvider
   
.state('product',{
       url
:"/product",
       templateUrl
: 'pages/product.html',
       controller
: 'productController'
     
});
}]);


/*
// configure our routes
gelovenIndia.config(function ($routeProvider,$locationProvider) {
    console.log("1");
    $locationProvider.hashPrefix('');
    $routeProvider


        // route for the Product page
        .when('/product', {
            templateUrl : 'pages/product.html',
            controller  : 'productController'
        });


}); */



gelovenIndia
.service('productService', function() {
    console
.log("2");
     
var product;


     
var addProduct = function(newObj) {
          console
.log("3");
          console
.log("adding product to service", newObj);
          product
= newObj;
     
};


     
var getProduct = function(){
          console
.log("4");
          console
.log("getting product from service", product);
         
return product;
     
};


     
return {
          addProduct
: addProduct,
          getProduct
: getProduct
     
};


   
});




gelovenIndia
.controller('productController', function($scope, $http, $location,$window, productService) {
    console
.log("In productController");
     $scope
.product = {};


      $scope
.productById = productService.getProduct();
      console
.log('Product in productController', $scope.productById);


      $scope
.onloadFun = function() {
            alert
(1);
            console
.log("In Onload Function");
            $http
({
                method
: 'GET',
                url
: 'productData',
                data
: angular.toJson($scope.userform),
                headers
: {
                   
'Content-Type' : 'application/json'
               
}
           
}).then(function(response) {
                alert
("Got response for Product Data");
                console
.log("Got response for Product Data");
                console
.log(response.data);
                $scope
.products = response.data;
           
});
       
};


        $scope
.getProductById = function(URL) {
            alert
("Product URL is :"+URL);
            console
.log('In getProductById');
            $scope
.product.product_Url = URL;
            console
.log($scope.product);
            $http
({
                method
: 'POST',
                url
: 'productData',
                data
: angular.toJson($scope.product),
                headers
: {
                   
'Content-Type': 'application/x-www-form-urlencoded'
               
}
           
}).then(function(response) {
                alert
("Got response for Product");
                console
.log("response in getProductById", response.data);
                $scope
.productById = response.data;
                productService
.addProduct(response.data);
                $location
.path('/product');
               
//$window.location.href = '/product';
                console
.log("10");


           
});
       
};


   
});


product.html is -


<body ng-controller="productController">
<div style="margin-top: 107px;">
       
<img src="{{product.product_Url}}" style="width:150px">
   
</div>
</body>

I am able to fetch product details from the server and able to get this data in controller function getProductById but I am not able to redirect this data to product.html. My redirection is not working from getProductById function.

Mickey Vashchinsky

unread,
Nov 24, 2017, 6:19:09 AM11/24/17
to Angular and AngularJS discussion
Hi.

There are many things in the code you posted that better be changed/updated (in my opinion).

  • For the app to function as multi page app you better use ngRouter (or ui-router) - it will handle the multiple pages and switching between them
  • If you read the Angular.js docs you will see that using ng-init is not recommended.
  • You are using POST to get product data, while usually REST approach is:
    • GET /products - gets all the products
    • GET /products/[:product_id] - gets the specific product by its ID

When you switch to using the ngRouter (ui-router) you probably will have a Controller (or a Component with a Controller) for each route.

In the products route you can fetch the products or in the Controller's constructor, or in $onInit function or in resolve of the route.
In the product details route you also can fetch the product by its ID or in the Controller's constructor, or in $onInit function or in resolve of the route.

You don't have to share data between 2 routes, each route will fetch the data it needs.

This is more theoretical, but of you interested I (or anyone else here) can guide you with the implementation.

Hope that helps.

Mickey Vashchinsky

unread,
Nov 24, 2017, 3:21:02 PM11/24/17
to Angular and AngularJS discussion
Here is a simplified mock of what the app can look like: https://plnkr.co/edit/fNN06PqbrekajnqkyhzR?p=preview


On Tuesday, November 21, 2017 at 9:31:56 AM UTC+2, abhishek srivastava wrote:

Mickey Vashchinsky

unread,
Nov 24, 2017, 3:26:31 PM11/24/17
to Angular and AngularJS discussion
And this is same mock but using router's resolvehttps://plnkr.co/edit/pN0kkkyqylM8jAj8iJGE?p=preview


On Tuesday, November 21, 2017 at 9:31:56 AM UTC+2, abhishek srivastava wrote:
Reply all
Reply to author
Forward
0 new messages