How can I know from and to where I'm browsing with ngRoute?

6

I have a template that is displayed temporarily, the problem with this is that it is displayed only if I click on a 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 URL /news/:id the controller sees if that value is saved, if so it does not show the temporary template, and if the value "does not is saved "then if it shows.

The controller would then 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 that you erase that value in the localStorage when you access it again, show the temporary template.

The problem is that I do not know how to implement something like that, I hope you can help me with an example, I'm new in this 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();
      }
    });
  });
    
asked by adrianojosue 04.09.2016 в 01:59
source

1 answer

4

You do not need localStorage to know which route you are coming from and where you are going (and to do a redirect based on a condition using that information). For this task ngRoute has an event $locationChangeStart .

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 parameters from and to will indicate how navigation is occurring. You can decompose those urls into parts and thus get 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 registers.

Basically the algorithm is if you get to /news/id and you do not come from /sponsor/id or the ids are not equal cancel the navigation.

    
answered by 06.09.2016 в 16:48