P
P
pLavrenov2015-11-09 01:57:26
JavaScript
pLavrenov, 2015-11-09 01:57:26

Why is the value of $routeParams not displayed in AngularJs?

I don't understand why the route1 variable is not displayed in the duo controller.
it writes undefined in the output, although it displays the variable in the one controller. and the object itself is displayed both there and there (route2 variables)

<!doctype html>
<html lang="ru" ng-app="app">
  <head>
    <base href="http://localhost:8080/">
    <script src="js/angular.min.js"></script>
    <script src="js/angular-route.min.js"></script>
    
    <script>
    
    var app = angular.module('app', ['ngRoute']);
      
    app.config(function($routeProvider, $locationProvider) {
      $routeProvider
      .when('/:text', {
        template:'<div>Controler one - 1 {{route1}} </br> Controler one - 2 {{route2}} </br> Controler one - 3 {{route3.text}}</div>',
        controller: 'one'
      });
      
      $locationProvider.html5Mode(true);
    });

    app.controller('one', ['$scope', '$routeParams', function($scope, $routeParams) {
      $scope.route1 = $routeParams.text;
      $scope.route2 = $routeParams;
      $scope.route3 = $routeParams;
    }]);

    app.controller('due', ['$scope', '$routeParams', function($scope, $routeParams) {
      $scope.route1 = $routeParams.text;
      $scope.route2 = $routeParams;
      $scope.route3 = $routeParams;
    }]);
    
    
    </script>
    
    
  </head>
  <body>

    
    <div class="content_in" ng-view></div>
    
    <div ng-controller="due">
      <b>Controler due - 1 {{route1}}</b> </br>
      Controler due - 2 {{route2}}  </br>
      Controler due - 3 {{route3.text}}  </br>
    </div>
    
  </body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
_
_ _, 2015-11-09
@AMar4enko

Because the one controller is instantiated after the router has worked. Therefore, when instantiated, $routeParams already has a parameter from the route.
The due controller is instantiated before the router has worked, so at the time of instantiation, $routeParams is empty and route1 is undefined. route2 and route3 are displayed because $routeParams is a reference to the same object during the entire life cycle of the application, you published it to the scope, when the route changes, the router publishes parameters to this object, they are displayed through two-way data binding.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question