ngView не отображает шаблоны

Я не могу отображать шаблоны в ng-view в своем угловом приложении, когда я запускаю его в разных браузерах или на локальном хосте, используя node. Консоль не выдает никаких ошибок. Я прочитал все, что мог найти в Интернете об этой проблеме, но ни один из них не является ответом на мою проблему. Я использую MacBook Pro с ОС El Capitan. Мне интересно, сделал ли я что-нибудь смешное со своим компьютером за последний год в качестве начинающего программиста, устанавливая sudo и запуская вещи без виртуальной среды. Или, может быть, здесь есть какая-то глупо очевидная ошибка, которую я проглядел, пробуя все перестановки, которые только мог придумать.

Это мой файл index.html:

   <!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
    <title>My App</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="stylesheet.css">

</head>

<body ng-app="OIApp">
     <nav id="mainnav" class="navbar navbar-inverse navbar-fixed-top">

        <div class="container"> 

            <div class="navbar-header">

            <a class="navbar-brand" href="#">
                <h1>My App</h1>
            </a>

            </div> 
            <ul class="nav navbar-nav navbar-right">

                <li class="active">
                    <a href="#/">Home</a>
                </li>
                <li>
                    <a href="#/about">About</a>
                </li>
                <li>
                    <a href="#/blog">Blog</a>
                </li>
                <li>
                    <a href="#/products">Products</a>
                </li>

            </ul>
        </div>
    </nav> 

        <div ng-controller="OIController1">
            <div ng-view>

            </div>

        </div>



    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular-route.min.js"></script>
    <script src="OIController.js"></script>
    <script src="OIApp.js"></script>
    <script src="config.js"></script>
    <script src="http://code.jquery.com/jquery.min.js"></script>
    <script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>

App.js выглядит так:

var app = angular.module("OIApp", ["ngRoute", "myControllers"])

Controller.js выглядит так:

   angular.module('myControllers', [])

.controller('OIController1', function($scope, $route) {
    $scope.names = [
        {name:"Colin Wilson", blurb: "Commodities are usually raw materials such as metals and agricultural products, but a commodity can also..."},
        {name:"Graham Hancock", blurb:"Commodities are usually raw materials such as metals and agricultural products, but a commodity can also..."},
        {name:"John Moriarty", blurb:"Commodities are usually raw materials such as metals and agricultural products, but a commodity can also ..."},
        {name:"William Thompson", blurb:"Commodities are usually raw materials such as metals and agricultural products, but a commodity can also..."} 
        ];

    }); 

Конфиг.js:

    angular.module('myRoutes', ['ngRoute', 'myControllers'])

.config('$routeProvider', function($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl : "/index.html",
        controller : "OIController1",
    })

    .when("/about", {
        templateUrl : "/about.html",
        controller : "OIController1"
    })

    .otherwise({
      redirectTo:'/'
    });

});

А это about.html, который я пытаюсь отобразить в ngView:

<div class="col-sm-2" ng-repeat="x in names">
    {{x.name}}
    {{x.blurb}}
</div>

person John Tangney    schedule 18.10.2016    source источник
comment
Попробуйте удалить '/' из templateUrl. т. е. templateUrl: 'about.html', templateUrl: 'index.html'   -  person Manish Singh    schedule 18.10.2016
comment
Пробовал, но похоже проблема не в этом.   -  person John Tangney    schedule 18.10.2016
comment
Вы также можете запустить мой ответ, используя приведенный ниже фрагмент, или щелкнуть ссылку на плункер, и вы получите решение.   -  person Sravan    schedule 18.10.2016


Ответы (2)


Есть несколько вопросов:

    //------------------------------------
    //Let say, it's a app.router.js
    //------------------------------------
     angular.module('myRoutes', ['ngRoute', 'myControllers'])
    .config(['$routeProvider', function($routeProvider) {
        $routeProvider
        .when("/", {
            templateUrl : "index.html",
            controller : "OIController1",
        })

        .when("/about", {
            templateUrl : "about.html",
            controller : "OIController1"
        })

        .otherwise({
          redirectTo:'/'
        });

    }]);

    //------------------------------------
    //Let say, it's a app.module.js
    //------------------------------------

    angular.module("OIApp", ["ngRoute", "myRoutes", "myControllers"]);

//------------------------------------
//Let say, it's a app.controller.js
//------------------------------------        

    angular.module('myControllers', [])
    .controller('OIController1', function($scope) {
        $scope.names = [
            {name:"Colin Wilson", blurb: "Commodities are usually raw materials such as metals and agricultural products, but a commodity can also..."},
            {name:"Graham Hancock", blurb:"Commodities are usually raw materials such as metals and agricultural products, but a commodity can also..."},
            {name:"John Moriarty", blurb:"Commodities are usually raw materials such as metals and agricultural products, but a commodity can also ..."},
            {name:"William Thompson", blurb:"Commodities are usually raw materials such as metals and agricultural products, but a commodity can also..."} 
            ];
        });

Я надеюсь, что это должно работать

person Manish Singh    schedule 18.10.2016
comment
Спасибо, но все еще получаю эту ошибку: angular.js:4640Uncaught Error: [$injector:modulerr] errors.angularjs.org/1.5.8/$injector/…udflare.com%2Fajax%2Flibs%2Fangular.js%2F1.5.8%2Fangular.min.js %3A20%3A390) - person John Tangney; 18.10.2016
comment
Эй, я вижу, у тебя был правильный ответ в отредактированной версии. Спасибо за вашу помощь. - person John Tangney; 18.10.2016

У вас синтаксическая ошибка, [] отсутствует в route provider.

Pls run the below snippet.

// Code goes here

var app = angular.module("OIApp", ["ngRoute", "myControllers"]);
  
  app.config(['$routeProvider', function($routeProvider) {
    $routeProvider
    .when("/", {
        
    })

    .when("/about", {
        templateUrl : "about.html",
        controller : "OIController1"
    })

    .otherwise({
      redirectTo:'/'
    });

}]);

var test = angular.module('myControllers', [])
test.controller('OIController1', function($scope, $route) {
    $scope.names = [
        {name:"Colin Wilson", blurb: "Commodities are usually raw materials such as metals and agricultural products, but a commodity can also..."},
        {name:"Graham Hancock", blurb:"Commodities are usually raw materials such as metals and agricultural products, but a commodity can also..."},
        {name:"John Moriarty", blurb:"Commodities are usually raw materials such as metals and agricultural products, but a commodity can also ..."},
        {name:"William Thompson", blurb:"Commodities are usually raw materials such as metals and agricultural products, but a commodity can also..."} 
        ];

    });
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
    <title>My App</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="stylesheet.css">

</head>

<body ng-app="OIApp">
  
  <script type="text/ng-template" id="about.html">
  <div class="col-sm-2" ng-repeat="x in names">
    {{x.name}}
    {{x.blurb}}
</div>
</script>
  
  <script>
  
  



  
</script>


     <nav id="mainnav" class="navbar navbar-inverse navbar-fixed-top">

        <div class="container"> 

            <div class="navbar-header">

            <a class="navbar-brand" href="#">
                <h1>My App</h1>
            </a>

            </div> 
            <ul class="nav navbar-nav navbar-right">

                <li class="active">
                    <a href="#/">Home</a>
                </li>
                <li>
                    <a href="#/about">About</a>
                </li>
                <li>
                    <a href="#/blog">Blog</a>
                </li>
                <li>
                    <a href="#/products">Products</a>
                </li>

            </ul>
        </div>
    </nav> 

        <div ng-controller="OIController1">
            <div ng-view>

            </div>

        </div>



    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular-route.min.js"></script>
    
    <script src="http://code.jquery.com/jquery.min.js"></script>
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <script src="script.js"></script>
</body>

</html>

Вот плункер

person Sravan    schedule 18.10.2016
comment
откройте плункер и перейдите по ссылкам index и about. - person Sravan; 18.10.2016
comment
Я впервые задаю вопрос о переполнении стека. Я проголосовал за ваш комментарий, но он сказал, что у меня недостаточно кредитов, чтобы зарегистрироваться в подсчете. Есть ли что-то еще, что мне нужно сделать? - person John Tangney; 18.10.2016
comment
Я интегрировал его со своим кодом, и сейчас шаблон отображается, хотя, похоже, он загружается очень медленно. Я сейчас на работе, так что не могу заниматься этим несколько часов. - person John Tangney; 18.10.2016
comment
хорошо, есть много способов dependency injection, пройтись по официальной документации. Пожалуйста, примите мой ответ, нажав на галочку. - person Sravan; 18.10.2016