您好,我正在尝试根据点击导航栏中的按钮来呈现新 View 。但是,它不起作用。
这是我的 HTML 代码:
<!-- Links to all the pages with data entry forms -->
<div id="data_links" ng-controller="MainCtrl">
<ul>
<li>
<a href="#" title="Home Page" ng-click = "ChangeView('instructions')"> Home </a>
</li>
</ul>
</div>
</div>
<!-- Modify views here -->
<div class="main" ng-controller="MainCtrl">
<main role="main">
<div ng-view> <!-- Where we will inject html --> </div>
</main>
</div>
<!-- Application Files -->
<script src="js/app.js"></script>
<script src="js/controllers/main.js"></script>
这是我的 app.js:
angular.module('DataEntry', [
'ngRoute'
]).config(function ( $routeProvider ) {
$routeProvider
.when('instructions', {
templateUrl: 'views/instructions.html',
controller: 'MainCtrl'
});
});
这是我的 Controller main.js:
angular.module('DataEntry')
.controller('MainCtrl',
function MainCtrl ( $scope, $location ) {
'use strict';
$scope.ChangeView = function(view) {
alert(view);
$location.url(view);
}
});
这是我的 instructions.html 页面,用于测试它是否加载:
<div class="module instructions">
<div class="module_instructions">
<h1> Testing Loaded! </h1>
<p> Test <br>
Test <br> Test <br> Test
</p>
</div>
</div>
我希望最终能够单击导航栏中的多个链接,例如主页、说明等,并在 ng-view 部分呈现不同的 View 。但是,它现在不工作,我不确定如何缩放它,以便我可以为我想要呈现的不同 View 添加更多 .html 页面。有人可以帮助我前进吗?
最佳答案
这一行
<a href="#" title="Home Page" ng-click = "ChangeView('instructions')"> Home
可以改成这样:
<a href="/instructions" title="Home Page"> Home </a>
您不需要在 Controller 上使用函数来设置 url,尽管您可以通过这种方式导航 - 有时您希望以编程方式重定向用户,这适用于这些情况。
另外,离开 href="#"
在那一行给你带来了问题。在非 Angular 页面中 # 用作 href 占位符,但在 Angular 页面上 href="#"
实际上会被$routeProvider
接走这将尝试更改 ng-view
的内容容器。负载将取决于您如何设置 .config
部分,但通常不是理想的行为。
当您创建更多页面时,将路径添加到您的 .config
部分,你可以从你的 html 链接到它们,就像我上面用 /instructions
做的一样。路径。
这是一个例子:
angular.module('DataEntry', ['ngRoute'])
.config(function ( $routeProvider ) {
$routeProvider
.when('instructions', {
templateUrl: 'views/instructions.html',
controller: 'MainCtrl'
})
.when('faq', {
templateUrl: 'views/faq.html',
controller: 'FaqCtrl'
})
.when('example', {
templateUrl: 'views/example.html',
controller: 'ExampleCtrl'
})
});
在你的标记中:
<a href="/instructions" title="Home Page"> Home </a>
<a href="/faq" title="FAQ"> FAQ</a>
<a href="/example" title="Example Page"> Example</a>
关于javascript - 基于单击按钮在 Div 中呈现新 View | AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28510567/