使用以下命令路由到AngularJS页面:id参数

时间:2015-12-03 15:03:59

标签: angularjs ngroute

我有一个AngularJS应用程序,它使用ngRoute来处理应用程序的路由。路由本身正在工作(URL被重定向到正确的页面并且正确的部分是打开的)但是,我无法在第二页中检索我需要的项目。

第一页允许您搜索文档列表(目前是虚拟的,但最终会链接到API)。列表项是可点击的,它将引导您到列出文档详细信息的第二页。

我将概述目前尝试实现这一目标的方式,但如果有人对如何改进此解决方案有任何想法,我愿意接受建议。

app.js

angular.module("app", ["ngRoute", "ngAnimate"])
.config(function($routeProvider){
    $routeProvider
        .when("/main", {
            templateUrl: "Views/main.html",
            controller: "MainController"
        })
        .when("/document/:id", {
            templateUrl: "Views/document.html",
            controller: "DocumentController"
        })
        .otherwise({redirectTo: "/main"});
});

main.html

<link rel="stylesheet" href="Stylesheets/main.css" type="text/css">

<div id="docSearchPanel" class="col-xs-12">
    <ng-include src="'Views/Partials/documentSearchForm.html'"></ng-include>
</div>

<div id="formSearchResultsArea">
        <div id="documentsFoundHeader">Documents Found</div>
    <div id="documentsTableContainer">
        <table id="documentsTable" class="table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="doc in documents" ng-click="showDocument()">
                    <td>{{doc.documentID}}</td>
                    <td>{{doc.documentTitle}}</td>
                    <td>{{doc.documentStatus}}</td>
                </tr>
            </tbody>
        </table>
    </div>

</div>

main.ctrl.js

angular.module("app").controller("MainController", function($scope, $location){

    //This is populated by a function I have removed to keep the code simple
    $scope.documents = []           

    $scope.showDocument = function(){
        $scope.activeDocument = this.doc;
        $location.path("document/"+this.doc.documentID);
    };
});

document.html

<form ng-submit="downloadForm()" class="col-xs-12 col-md-6">
    <h2>Document Details</h2>
    <div class="row">
        <h3>{{activeDocument.documentTitle}}</h3>
    </div>
    <div class="row" ng-repeat="field in selected.fields">  
        <div class="form-group">
            <div class="document-attribute-header col-xs-5">{{field.key}}</div>
            <div class="document-attribute-value col-xs-7">{{field.val}}</div>
        </div>
    </div>
</form>

document.ctrl.js

angular.module("app").controller("DocumentController", function($scope, $location, $routeParams){
    $scope.activeDocument = getActiveDocument($routeParams.id);

    function getActiveDocument(id){
        for (var d in $scope.documents){
            var doc = $scope.documents[d];
            if (doc.documentID == id)
                return doc;
        }
    }
});

0 个答案:

没有答案