Nasir
Nasir

Reputation: 4865

Angular: How do I pass data between 2 views of a single page app?

This is my first attempt at Angular.js. I am attempting to create a single page app which load some JSON and displays a list. When I click a link in the list it should go to a new page and populate the page in greater detail via the id from the JSON data.

Any help is massively appreciated.

Here is the JavaScript (easyjet.js):

    var app = angular.module('easyjet', ['ui.router']);

app.config(function($stateProvider, $urlRouterProvider){
    $stateProvider.state('flights', {
        url: '/', 
        templateUrl: 'templates/list.html',
        controller: 'ResultsController'
    })
    .state('details', {
        url: '/detail/:id',
        templateUrl: 'templates/fulldetails.html',
        controller: 'ResultsController'
    });
    $urlRouterProvider.otherwise('/');
});


app.controller('ResultsController', function($scope, $http, $stateParams) {

    console.log($stateParams); 

    // Get JSON data
    $http({
        method : "GET",
        url : "http://ejtestbed.herokuapp.com/flights"
    }).then(function(response) {
        $scope.resultsData = response.data;
    }, function(response) {
        $scope.resultsData = response.statusText;
        console.log("Oops! Couldn't load JSON!");
    });

    // Select and display result details
    $scope.selectedResult = null;

    $scope.selectResult = function (result) {
        $scope.selectedResult = result;
    };

    //Sorting default setting
    $scope.order = "flightNumber.number";

});

Here is the default HTML page:

<!DOCTYPE html>
<html ng-app="easyjet">
    <head>
        <meta charset="utf-8" />
        <title>Easyjet, Flights</title>
    </head>
    <body>
        <div ui-view></div>

        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
        <script src="angular-ui-router.min.js"></script>
        <script src="easyjet.js"></script>  
    </body>
</html>

The template files: 1. list.html

<div class="container">

    <!-- Filtering & Sorting -->
    <div>
        <input type="text" id="search" ng-model="search.$" placeholder="Search anything..." />
        <select ng-model="order">
            <option value="flightNumber.number">Flight Number (ASC)</option>
            <option value="-flightNumber.number">Flight Number (DEC)</option>
            <option value="localDepartureTime">Date (ASC)</option>
            <option value="-localDepartureTime">Date (DEC)</option>
        </select>
    </div>

    <!-- Result List -->
    <div class="result" 
        ng-repeat="result in filteredResults = (resultsData | filter: search | orderBy: order)" 
        ng-style="{ 'background-color': result.id == selectedResult.id ? 'lightgray' : '' }"
        ng-click="selectResult(result)">

        <span style="display:none;">{{ $index }}</span>
        <a ng-href="#/detail/{{ result.id }}"><span>EZY {{ result.flightNumber.number }}</span></a>
        <span>From: {{ result.departureAirport }}</span> 
        <span>To: {{ result.arrivalAirport }}</span>
        <span>Date: {{ result.localDepartureTime | date:"longDate" }}</span>
    </div>

    <div ng-show="filteredResults.length == 0">No Result Found</div>

</div>
  1. fulldetails.html

Upvotes: 1

Views: 294

Answers (3)

Jorawar Singh
Jorawar Singh

Reputation: 7621

If you are Using same controller then you can store your data in cache or local-storage other wise if you use service to store data and same controller it will break because service will also be reloaded and loose the data if you are not using same controller then you should definitely use service as best practice

How to work with cache? use $cacheFactory in controller

check on controller loaded

 var yourCache = $cacheFactory.get('yourCache') || $cacheFactory('searchCache'); 

in your function after success just save to cache

yourCache.put(key, value);

and for removing it

yourCache.remove('key');

Upvotes: 0

Syam Pillai
Syam Pillai

Reputation: 5217

You can use angular service to share the variable with two ore more controllers

But here your problem is to share the values between views that having same controller.

Here when ever you are changing the view, the controller reloads. So you have to store that value in local storage or session storage (even though we can setup a service, better option is localStorage or sessionStorage).

For this you can use $localStorage or $sessionStorage dependencies.

Upvotes: 0

Galhem
Galhem

Reputation: 215

You should use a service which will do the call and store the data between the pages.

Your controllers will call this service to get the data or ask to refresh it.

Upvotes: 4

Related Questions