根据元素的href使用ng-include渲染div中页面的内容? [英] Rendering the content of a page inside a div using ng-include based on the href of an element?
问题描述
如果我有两个列表项
<li><a href="foo.html"></a></li>
<li><a href="bar.html"></a></li>
并基于单击哪个,使用ng-include在当前页面的div中呈现?
and based on which is clicked, to use ng-include to render in a div on the current page?
<div ng-controller="main-panel" class="main-panel">
<ng-include src="'clickedElement'"></ng-include>
</div>
我对如何使用路由在div中呈现html感到困惑,这取决于您单击哪个元素?
I am confused as to how to use routes to render an html inside a div, which is decided by which element you click?
main.config(function ($routeProvider, $locationProvider, $httpProvider) {
$routeProvider
.when('/', {
controller: 'side-menu'
})
.when('/signup', {
templateUrl : 'signup.html',
controller: 'main-panel'
});
$locationProvider.html5Mode(true);
});
HTML
<li ng-repeat="oucampus in secondaryLinks.oucampus">
<a ng-href='{{oucampus.href}}'> {{oucampus.title}} </a>
</li>
<div class="main-panel" ng-view></div>
控制器功能
oucampus: [
{title: "Requests", href:"signup.html"},
],
推荐答案
如果您尝试基于路由呈现HTML内容,则需要使用诸如 UI路由器.在Angular应用程序中, ng-include
不是实现路由的最佳选择.
If you are trying to render HTML content based on routes, you would want to use a routing service such as ngRoute or ui-router. ng-include
isn't the best option for implementing routing within your angular application.
使用 ngRoute
,您可以使用指令 ng-view
根据应用程序中指定/配置的路由对角负载html/controllers/etc进行配置 config()
方法添加到某些DOM元素中.当您单击具有 ng-href
且具有相应路径的< a>
时,或使用 $ location在诸如控制器之类的程序中单击时,会触发此事件.
服务 path()
方法.
With ngRoute
, you use a directive ng-view
to have angular load html/controllers/etc based on route specified/configured in your applications config()
method into some DOM element. This is triggered when you click on an <a>
that has an ng-href
with a corresponding path or programatically in something like a controller using the $location
service path()
method.
路由配置:
app.config(function($routeProvider) {
$routeProvider
.when('/foo', {
templateUrl: 'foo.html',
controller: 'FooController'
})
.when('/bar', {
templateUrl: 'bar.html',
controller: 'BarController'
});
});
HTML:
<ul>
<li><a ng-href="#/foo">foo</a></li>
<li><a ng-href="#/bar">bar</a></li>
</ul>
<div ng-view></div>
这是 plunker ,它演示了基本路由的功能,包括加载特定的控制器和基于特定路由的HTML模板.
Here is a plunker demonstrating the functionality of basic routing including loading specific controllers and HTML templates based on a specific route.
ng-include 如果您绝对需要使用 ng-include
,则可以使用通过附加到$ scope或controllerAs的 ng-click
执行的函数来更新 src
ng-include 的>属性,以基于click元素加载模板.我已经更新了 plunker .
ng-include
If you absolutely need to use ng-include
, you can using a function executed via ng-click
attached to $scope or controllerAs to update the src
property of ng-include
to load a template based on a click element. I've updated the plunker.
希望这会有所帮助!
这篇关于根据元素的href使用ng-include渲染div中页面的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!