角度 - 页面加载时不加载主视图

时间:2014-11-11 12:11:06

标签: angularjs angularjs-routing

我是Angular的新手,我正在尝试使用路线构建个人网站来更改视图。

我已经能够让导航器将类更改为活动状态,具体取决于所点击的内容,但现在我遇到的问题是当页面加载时主视图不会加载(一切都在点击时工作) 。

如果有人可以提供帮助,我真的很感激。如果我犯了任何愚蠢的错误,请告诉我。

另外,我在控制器div外面有视图,它应该在里面吗? 谢谢 HTML:

'use strict';
angular.module('myApp', [
    'ngAnimate',
    'ngAria',
    'ngCookies',
    'ngMessages',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch'
  ])
var myApp = angular.module('myApp', []);


myApp.config(function($routeProvider) {
       
    $routeProvider
    .when('/main', {templateUrl:'views/main.html', controller:'WidgetsController'})
    .when('/about', {templateUrl:'views/about.html', controller:'WidgetsController'})
	.otherwise({
        redirectTo: '/'
      });
});


myApp.controller('WidgetsController', function($scope) {});
myApp.controller('MyCtrl', function($scope, $location) {
    $scope.isActive = function(route) {
        return route === $location.path();
    }
});
<body ng-app="myApp" class="ng-scope">
    
          
       <div ng-controller="MyCtrl" class="ng-scope">
    <ul class="nav nav-pills pull-right">
          
        <li ng-class="{active:isActive('/main')}"><a href="#/main">Main</a></li>
        <li ng-class="{active:isActive('/about')}"><a href="#/about">About</a></li>
    </ul> </div>  </div> </div>
    
    <div ng-view=""></div>

1 个答案:

答案 0 :(得分:0)

请参阅下面的工作示例

你已经为myApp定义了两次,确保你所有人都参考了你的“主页”中的所有角度模块

'use strict';

var myApp = angular.module('myApp', ['ngRoute']);


myApp.config(function($routeProvider) {

  $routeProvider
    .when('/main', {
      templateUrl: 'views/main.html',
      controller: 'WidgetsController'
    })
    .when('/about', {
      templateUrl: 'views/about.html',
      controller: 'WidgetsController'
    })
    .otherwise({
      redirectTo: '/main'
    });
});


myApp.controller('WidgetsController', function($scope) {});
myApp.controller('MyCtrl', function($scope, $location) {
  $scope.isActive = function(route) {
    return route === $location.path();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.3/angular-route.min.js"></script>

<body ng-app="myApp" class="ng-scope">


  <div ng-controller="MyCtrl" class="ng-scope">
    <ul class="nav nav-pills pull-right">

      <li ng-class="{active:isActive('/main')}"><a href="#/main">Main</a>
      </li>
      <li ng-class="{active:isActive('/about')}"><a href="#/about">About</a>
      </li>
    </ul>
  </div>



  <div ng-view=""></div>

  <script type="text/ng-template" id="views/main.html">
    <h1>Main View</h1>
  </script>
  <script type="text/ng-template" id="views/about.html">
    <h1>About View</h1>
  </script>