简体   繁体   English

angular.js:如何使用模板和JSON构建SPA

[英]angular.js: How to use templates and JSON for building a SPA

I'm using angular.js to create a SPA. 我正在使用angular.js创建SPA。 I need your advise which technique I have to use for showing the informations/articles. 我需要您的建议,我必须使用哪种技术来显示信息/文章。

My index.html looks like this: 我的index.html看起来像这样:

<body>
    <header id="navigation">
        <nav id="main">
            <ul>
                <li id="login"><button class="btn">Login</button></li>
            </ul>
        </nav>
    </header>
    <main>

    </main>
    <footer>
        <p>Some text</p>
    </footer>
</body>

At the beginning this HTML (using the directive angucomplete-alt) should be shown in the main-container: 首先,该HTML(使用指令angucomplete-alt)应显示在main-container中:

autocomplete-search-template.html: 自动完成搜索,template.html:

<div>Any content</div>
<div id="searching" ng-controller='search'>
    <div angucomplete-alt id="s1" selected-object="select" remote-url="search.php?q=" remote-url-data-field="results" title-field="title" description-field="description"></div>
</div>

When the user is searching for an article the following controller is used: 当用户搜索文章时,将使用以下控制器:

controller: 控制器:

app.controller('search', ['$scope', '$http',
    function s1($scope, $http) {

        $scope.select = function(selected) {
            if (selected) {
                /* Article has been chosen */
            }
        };

    }
]);

The article-template.html looks like this and should be inserted into the main-container, after the user has selected an article in the search (angucomplete-alt: article-template.html看起来像这样,当用户在搜索中选择了文章后,应将其插入到主容器中(angucomplete-alt:

article-template.html: 文章-template.html:

<article>
    <header>{{title}}</header>
    <div>{{content}}</div>
</article>

Now I don't know how I should put this parts together and therefore I need your help. 现在我不知道如何将这些零件放在一起,因此我需要您的帮助。

  1. How do I put these templates together? 如何将这些模板放在一起? (a) Do I have to use routing or is there another technique? (a)我必须使用路由还是有其他技术? If I have to use routing, then I don't know how to get from the search-result to the article-display as it is no href-link... (b) Or would it be better to use ng-include (c) Or another option? 如果我必须使用路由,那么我不知道如何从搜索结果转到文章显示,因为它不是href链接...(b)还是使用ng-include( c)还是其他选择?
  2. Where (and when) do I get the article informations? 我从哪里(何时)获得文章信息? I think I have to use a http-post request to get a JSON-array which will be used to fill the placeholders of article-template.html. 我想我必须使用http-post请求来获取JSON数组,该数组将用于填充article-template.html的占位符。 So I thought of doing a request in the $scope.select . 所以我想到了在$scope.select中进行请求。 But there is still my problem of merging everything together 但是仍然存在我将所有内容合并在一起的问题

Update Routing: 更新路由:

app.config(function($routeProvider) {
    $routeProvider
    .when('/search', {
        templateUrl: 'autocomplete-search-template.html',
        controller: 'search'
    })
    .otherwise({
        redirectTo: '/search'
    });
});

This is working to show the autocomplete-search-template.html at the frontpage. 这是为了在首页显示autocomplete-search-template.html。 But I don't know how to route for the results of the angucomplete-alt search. 但是我不知道如何路由angucomplete-alt搜索的结果。

With Angular ui-router you can use a nested view for your search result. 使用Angular ui-router,您可以将嵌套视图用于搜索结果。

To get your data before the view is loaded you can use resolve to get the data from server. 要在加载视图之前获取数据,可以使用resolve从服务器获取数据。 Then you can inject the resolved promise into you controller and use the returned data in your nested view. 然后,您可以将解析的Promise注入到控制器中,并在嵌套视图中使用返回的数据。

With $state.go('search.article', {foundArticle: $scope.selectedPerson}); 使用$state.go('search.article', {foundArticle: $scope.selectedPerson}); you can pass the selected item from angucomplete to the nested view. 您可以将所选项目从angucomplete到嵌套视图。

To make the paramter passing work you need to add the following to the nested view: 为了使参数传递工作正常进行,您需要在嵌套视图中添加以下内容:

$stateProvider.state('search.article', {
    ...
    params:{foundArticle:null},
    controller: function ($scope, $stateParams) {
        $scope.article = $stateParams.foundArticle;
    }
}

For an example of the usage see the demo below (code not working here on SO - 'operation is insecure' issue. Don't know how to fix.) and here at jsFiddle . 有关用法的示例,请参见下面的演示(代码在此处不适用于SO-“操作不安全”问题。不知道如何解决。)以及在jsFiddle处

The code could be improved at the following points: 该代码可以在以下几点进行改进:

  • Using a service for getting the data. 使用服务获取数据。
  • If your articles are large you probably need to do another resolve at transition to the article and load at pageload only the needed data. 如果您的文章很大,则在过渡到文章时可能需要执行其他解决方案,并仅在页面加载时加载所需的数据。 The demo loads everything at the beginning. 该演示会在开始时加载所有内容。

 angular.module('myApp', ['ui.router', 'angucomplete-alt']) .controller('search', function ($scope, $state, searchData) { //console.log(searchData.data); $scope.people = searchData.data; // static dummy data below /*$scope.people = [ {firstName: "Susan", surname: "Rowland", twitter: "@susanrowland", pic: "http://lorempixel.com/100/100/people/1/", content: 'text for Susan'}, {firstName: "Alan", surname: "Partridge", twitter: "@alangpartridge", pic: "http://lorempixel.com/100/100/people/3/", content: 'text for Alan'}, {firstName: "Annie", surname: "Rowland", twitter: "@anklesannie", pic: "http://lorempixel.com/100/100/people/6/", content: 'text for Annie'} ];*/ $scope.select = function(selected) { if (selected) { console.log(selected, $state); /* Article has been chosen */ $scope.selectedPerson = selected; // same as two-way binding $state.go('search.article', {foundArticle: $scope.selectedPerson}); } }; }) .config(function ($stateProvider, $urlRouterProvider) { // // For any unmatched url, redirect to /state1 $urlRouterProvider.otherwise("/search"); // // Now set up the states $stateProvider.state('search', { url: "/search", resolve: { searchData: function ($http) { return $http.jsonp('http://www.mocky.io/v2/554f135e539c140e02858ff7/?callback=JSON_CALLBACK'); } }, templateUrl: "partials/search.html", controller: 'search' }) .state('search.article', { url: "/article", params:{foundArticle:null}, templateUrl: "partials/search.article.html", controller: function ($scope, $stateParams) { $scope.article = $stateParams.foundArticle; } }) }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.14/angular-ui-router.min.js"></script> <script src="https://raw.githubusercontent.com/ghiden/angucomplete-alt/master/dist/angucomplete-alt.min.js"></script> <script type="text/ng-template" id="partials/search.html"> <!-- partials/state1.html --> <h1>Search users (eg Rowland)</h1> <hr/> <!--<a ui-sref="state1.list">Show List</a>--> <div angucomplete-alt id="ex2" placeholder="Search people" pause="300" selected-object="select" local-data="people" search-fields="firstName,surname" title-field="firstName,surname" description-field="twitter" image-field="pic" minlength="1" input-class="form-control form-control-small" match-class="highlight"> </div> <div class="result"> <div class="" ng-show="selectedPerson" > You selected <span class="bold-span">{{selectedPerson.originalObject.firstName}} {{selectedPerson.originalObject.surname}}</span> </div> </div> <div ui-view></div> </script> <script type="text/ng-template" id="partials/search.article.html"> <h3>Found article</h3> <article> <header>{{article.title}}</header> <div> <p>{{article.originalObject.content}}</p> <pre>{{article | json}}</pre></div> </article> </script> <div ng-app="myApp"> <div ui-view=""></div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM