Контроллер AngularJS неправильно загружен во время ng-Route () - PullRequest
1 голос
/ 18 октября 2019

Я изучаю пример одностраничного приложения, использующего angularjs. Вот соответствующий код:

index.html

<!DOCTYPE html>
<html ng-app="app">
<head>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
    <script>
        var app = angular.module('app', ['ngRoute']);
        app.config(function ($routeProvider) {
        // configure the routes
        $routeProvider
        .when('/', {
        // route for the home page
        templateUrl: 'pages/home.html',
        controller: 'homeController'
        })
        .when('/about/', {
        // route for the about page
        templateUrl: 'pages/about.html',
        controller: 'aboutController'
        })
        .when('/contact/', {
        // route for the contact page
        templateUrl: 'pages/contact.html',
        controller: 'contactController'
        })
        .otherwise({
        // when all else fails
        templateUrl: 'pages/routeNotFound.html',
        controller: 'notFoundController'
        });
        });
        app.controller('homeController', function ($scope) {
            $scope.message = 'Welcome to my home page!';
        });
        app.controller('aboutController', function ($scope) {
            $scope.message = 'Find out more about me.';
        });
        app.controller('contactController', function ($scope) {
            $scope.message = 'Contact us!';
        });
        app.controller('notFoundController', function ($scope) {
            $scope.message = 'There seems to be a problem finding the page you wanted';
            $scope.attemptedPath = $location.path();
        });
    </script>
</head>
<body ng-controller="homeController">
    <header>
        <nav class="navbar navbar-default">
            <div class="container">
                <div class="navbar-header">
                    <a class="navbar-brand" href="/">My Website</a>
                </div>
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#"><i class="fa fa-home"></i> Home</a></li>
                    <li><a href="#!about"><i class="fa fa-shield"></i> About</a></li>
                    <li><a href="#!contact"><i class="fa fa-comment"></i> Contact</a></li>
                </ul>
            </div>
        </nav>
    </header>
    <div id="main">
        <!-- this is where content will be injected -->
        <div ng-view></div>
    </div>
</body>
</html>

routeNotFound.html

<div class="jumbotron text-center">
    <h1>This is not good</h1>
    <p>{{message}}</p>
    <p class="has-error">{{attemptedPath}}</p>
</div>

Когда я нажимаю на Home или About или Contact, страница отображается правильно. Но если я захожу на любой другой URL, routeNotFound.html правильно вводится в div [ng-view], но данные не связаны. Я получаю:

This is not good
{{message}}

{{attemptedPath}}

Кажется, notFoundController неправильно сделан доступным для представления, когда .otherwise () вызывается внутри маршрута. $ scope.message и $ scope.attemptedPath не привязаны к представлению.

1 Ответ

0 голосов
/ 18 октября 2019

Вам не хватает $ locationService инъекций в ваш notFoundController

app.controller('notFoundController', function ($scope,$location /*<--- location injected here*/) {
            $scope.message = 'There seems to be a problem finding the page you wanted';
            $scope.attemptedPath = $location.path();
        });

Вот полный пример:

var app = angular.module('app', ['ngRoute']);
		app.config(function ($routeProvider) {
		// configure the routes
		$routeProvider
		.when('/', {
		// route for the home page
		template: '<h1>My page home</h1><br />{{message}}',
		controller: 'homeController'
		})
		.when('/about/', {
		// route for the about page
		template: '<h1>My page about</h1><br />{{message}}',
		controller: 'aboutController'
		})
		.when('/contact/', {
		// route for the contact page
		template: '<h1>My page contact</h1><br />{{message}}',
		controller: 'contactController'
		})
		.otherwise({
		// when all else fails
	template: '<h1>Not found page</h1><br />{{message}}',
		controller: 'notFoundController'
		});
		});
		app.controller('homeController', function ($scope) {
			$scope.message = 'Welcome to my home page!';
		});
		app.controller('aboutController', function ($scope) {
			$scope.message = 'Find out more about me.';
		});
		app.controller('contactController', function ($scope) {
			$scope.message = 'Contact us!';
		});
		app.controller('notFoundController', function ($scope,$location) {
			$scope.message = 'There seems to be a problem finding the page you wanted';
			$scope.attemptedPath = $location.path();
		});
<!DOCTYPE html>
<html ng-app="app">
<head>
	<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"/>
	<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css"/>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
	<script>
		
	</script>
</head>
<body ng-controller="homeController">
	<header>
		<nav class="navbar navbar-default">
			<div class="container">
				<div class="navbar-header">
					<a class="navbar-brand" href="/">My Website</a>
				</div>
				<ul class="nav navbar-nav navbar-right">
					<li><a href="#"><i class="fa fa-home"></i> Home</a></li>
					<li><a href="#!about"><i class="fa fa-shield"></i> About</a></li>
					<li><a href="#!contact"><i class="fa fa-comment"></i> Contact</a></li>
          <li><a href="#!notsdflj"><i class="fa fa-comment"></i> Not found</a></li>
				</ul>
			</div>
		</nav>
	</header>
	<div id="main">
		<!-- this is where content will be injected -->
		<div ng-view></div>
	</div>
</body>
</html>
...