一个Angular页面,包含许多url:s

时间:2015-11-03 18:15:40

标签: angularjs

我有一个简单的Angular应用程序(出于培训目的,因为我是一个Angular-rookie :)),其中包含一些包含一些书籍的ul-list。如果用户点击某本书,则会在列表下方显示详细信息视图,其中包含有关该图书的一些详细信息。我希望如果用户点击该书,则该网址应更改为/#/ [book-id]。用户当然也应该能够直接浏览到这个URL,其中可以看到特定书籍的详细信息视图。我还没弄清楚如何用路线做这件事。我在下面粘贴我的示例代码:

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    </head>
    <body ng-app="libraryApp">
        <div id="list" ng-controller="listCtrl">
            <ul ng-repeat="book in data.list">
                <li><a href="" ng-click="openDetailView(book)">{{ book.name }}</a></li>
            </ul>
        </div>
        <div id="detailView" ng-controller="detailCtrl">
            <div  ng-if="data.currentBook" style="background-color: #EEE; padding: 10px 0;">
                <h1>{{ data.currentBook.name }}</h1>
                <div>Number of pages: {{ data.currentBook.pages }}</div>
            </div>
        </div>
    </body>
</html>

<script>
    angular.module("libraryApp", [])

     .factory("dataFactory", function() {
        return {
            list: [
                    { id: 1, name: "The Great Gatsy", pages: 423 },
                    { id: 2, name: "1984", pages: 332 },
                    { id: 3, name: "The Lord Of The Rings", pages: 632 }
                ],
            currentBook: null
        };
     })

    .controller("listCtrl", function($scope, dataFactory) {
        $scope.data = dataFactory;
        $scope.openDetailView = function(book) {
            $scope.data.currentBook = book;
        };
    })

    .controller("detailCtrl", function($scope, dataFactory) {
        $scope.data = dataFactory;
    });
</script>   

3 个答案:

答案 0 :(得分:0)

有点难以回答,因为有很多方法可以做到这一点,但请看https://github.com/angular-ui/ui-router

您将使用模块的config块来设置$stateProvider的路由,然后指定您在用户时要使用的控制器和模板改变应用程序的状态。这意味着您可能需要将针对不同视图的div移动到单独的文件(或创建内容以获取其内容的内容 - 使用jQuery获取元素的html或其他可行的内容。

我没有详细介绍,因为现在你知道使用ui-router,这是很容易回答的问题:)

答案 1 :(得分:0)

它被称为嵌套视图。要使用它,您最好尝试使用ui-router:https://angular-ui.github.io/ui-router/sample/#/contacts/1/item/b

答案 2 :(得分:0)

你必须把这段代码放在你的代码中......

angular.module(“libraryApp”,['ngRought'])

.config(function ($routeProvider)

{

$ routeProvider

.when("/bookname",
{
        templateUrl: "path of the html file",
        controller: "listCtrl"
    })
.when("/date",
{
        templateUrl: "path of the html file",
        controller: "detailCtrl"
    })