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

#javascript #angularjs #ng-view

#javascript #angularjs #ng-view

Вопрос:

Я не могу отображать шаблоны в ng-view в моем приложении angular, когда я запускаю его в разных браузерах или на локальном хосте с помощью 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..."} 
        ];

    }); 
  

Config.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>
  

Комментарии:

1. Попробуйте удалить ‘/’ из templateUrl. т.е. templateUrl: ‘about.html ‘, templateUrl: ‘index.html ‘

2. Пробовал, но, похоже, это не проблема.

3. Вы также можете запустить мой ответ, используя приведенный ниже фрагмент, или щелкнуть ссылку на плунжер, и вы получите решение.

Ответ №1:

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

     //------------------------------------
    //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..."} 
            ];
        });
  

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

Комментарии:

1. Спасибо, но все еще получаю эту ошибку: ошибка angular.js:4640Uncaught: [$injector:modulerr] errors.angularjs.org/1.5.8/$injector/. …..udflare.com/ajax/libs/angular.js/1.5.8/angular.min.js:20:390)

2. Эй, я вижу, у вас был правильный ответ в вашей отредактированной версии. Спасибо за вашу помощь.

Ответ №2:

У вас синтаксическая ошибка, [] отсутствует 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>  

Вот плунжер

Комментарии:

1. откройте плунжер и перейдите по index about ссылкам и.

2. Я впервые задаю вопрос о переполнении стека. Я поддержал ваш комментарий, но в нем говорилось, что у меня недостаточно кредитов для его регистрации при подсчете. Есть ли что-то еще, что мне нужно сделать?

3. Я интегрировал его в свой код, и теперь шаблон отображается, хотя, похоже, он загружается очень медленно. Я сейчас на работе, поэтому не могу заниматься этим в течение нескольких часов.

4. хорошо, есть много способов dependency injection , ознакомьтесь с официальной документацией. пожалуйста, примите мой ответ, нажав на галочку.