javascript – How can I know from and where I am navigating with ngRoute

Question:

I have a template that is displayed temporarily, the problem with this is that it is displayed only if I click on an already predefined link.

What I want to do is that the temporary template is displayed when accessing the URL with id (/news/:id) automatically.

I think this could be implemented by saving a value with localStorage , so if I visit the /news/:id URL the controller sees if that value is saved, if so then it doesn't show the temporary template, and if the value is "not saved" so if it shows.

What the controller would then do is save the value in localStorage if it is not and show the temporary template for 5 seconds, then when the temporary template redirects me to the URL with id that I should have accessed from the beginning, delete that value in the localStorage for when you access again show the temporary template.

The problem is that I don't know how to implement something like that, I hope you can help me with an example, I'm new to programming.

<a ng-href="/news/{{item.id}}/sponsor"></a>
app.config(['$routeProvider', '$locationProvider', function($routeProvider,$locationProvider){
    $routeProvider
      .when('/news/:id',{
        templateUrl: 'html/article.html',
        controller: 'articleCtrl',
        controllerAs: 'article',
        title: 'Artículo'
      })
      .when('/news/:id/sponsor',{
        templateUrl: 'html/sponsor.html',
        controller: 'sponsorCtrl',
        controllerAs: 'sponsor',
        title: 'Patrocinador'
      });
      $locationProvider.html5Mode(true).hashPrefix('!');
  }]);

app.controller('sponsorCtrl', ['$scope','$interval','$location','$routeParams',
  function($scope, $interval, $location, $routeParams) {
    var promise;
    $scope.time = 5;

    promise = $interval(function() {
      $scope.time = $scope.time - 1;
      if ($scope.time === 0) {
        $location.url('/news/' + $routeParams.id)
      }
    }, 1000, $scope.time);

    $scope.$on('$destroy', function() {
      $interval.cancel(promise);
    });
  }]);

  app.run(function($rootScope, $location, $routeParams) {
    $rootScope.$on('$locationChangeStart', function(evt, to, from) {
      var toRegExp = '/news/' + $routeParams.id;
      var fromRegExp = '/news/' + $routeParams.id + '/sponsor';
      var toMatch = toRegExp.exec(to);
      var fromMatch = fromRegExp.exec(from);
      if (toMatch && (!fromMatch || toMatch[1] !== fromMatch[1])) {
        evt.preventDefault();
        $location.path('/news/' + $routeParams.id + '/sponsor').replace();
      }
    });
  });

Answer:

You don't need localStorage to know which route you came from and where you're going (and do a redirect based on a condition using that information). For this task ngRoute has a $locationChangeStart event.

angular.module('app', ['ngRoute'])
  .config(function($routeProvider) {
    $routeProvider
      .when('/', {
        template: '<h1>Seleccione una página para navegar</h1><p>Ir a <a href="#/news/1">news 1</a></p><p>Ir a <a href="#/sponsor/1">sponsor 1</a></p>'
      })
      .when('/news/:id', {
        template: '<h1>News</h1>'
      })
      .when('/sponsor/:id', {
        template: '<h1>Sponsor</h1><p>Ir a <a href="#/news/1">news 1</a></p><p>Ir a <a href="#/news/2">news 2</a></p>'
      })
      .otherwise({
        redirectTo: '/'
      });
  })
  .run(function($rootScope, $location) {
    $rootScope.$on('$locationChangeStart', function(evt, to, from) {
      console.log('Navegando');
      console.log('desde:', from);
      console.log('hasta:', to);

      var toRegExp = /http:\/\/stacksnippets\.net\/js#\/news\/(\d+)/;
      var fromRegExp = /http:\/\/stacksnippets\.net\/js#\/sponsor\/(\d+)/;
      var toMatch = toRegExp.exec(to);
      var fromMatch = fromRegExp.exec(from);

      if (toMatch && (!fromMatch || toMatch[1] !== fromMatch[1])) {
        console.log('Mala navegación detectada')
        evt.preventDefault();
        $location.path('/sponsor/' + toMatch[1]);
      }
    });
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-route.min.js"></script>
<div ng-app="app">
  <div ng-view></div>
</div>

The from and to parameters will tell you how the navigation is happening. You can decompose those urls into parts and thus extract all the information you need from them.

In the example I'm using regular expressions for that or you can use the split('/') method and look at the last two records.

Basically the algorithm is if you get to /news/id and you don't come from /sponsor/id or the ids are not the same you cancel the navigation.

Scroll to Top
AllEscort