Build a Pokemon management system from scratch (2) - Realize details page jump with ngRoute

1. Goal

Last time we used Angular1.x to complete a simple Pokemon display list page , now we want to know more information about Pokemon, but found that the original one-line table may not hold all the information of Pokemon, so now we need a pocket Monster details interface. Still starting from the display list interface just now, click the name of the Pokemon and jump to the specified Pokemon information interface.

2. Analysis

If you want to jump from the list page to the details interface after clicking the name, the most primitive way must be to use the <a> tag to add links and parameters to jump to the new interface , but now we want to smoothly transition from the original interface to the new interface. That is to use routing to achieve view transfer, then very simply we found the officially provided routing jump module ngRoute .

To use routing, the first step is to import js and reference the routing module in app.js, then configure the routing, and finally write the interface and interface logic. Let's start coding~

3. Development

  1. data preparation

First, expand the pokemons data in the original app.js:

var pokemons = [ { no:'001', name:'妙蛙种子', count: 1, weight: 6.9, property: '草/毒', type: '种子宝可梦', character: { common: '茂盛', conceal: '叶绿素'}}, { no:'002', name:'妙蛙草', count: 1, weight: 13.0, property: '草/毒', type: '种子宝可梦', character: { common: '茂盛', conceal: '叶绿素'}}, { no:'003', name:'妙蛙花', count: 1, weight: 100, property: '草/毒', type: '种子宝可梦', character: { common: '茂盛', conceal: '叶绿素'}}, { no:'004', name:'小火龙', count: 1, weight: 8.5, property: '火', type: '蜥蜴宝可梦', character: { common: '猛火', conceal: '太阳之力'}}, { no:'025', name:'皮卡丘', count: 1, weight: 6, property: '电', type: '鼠宝可梦', character: { common: '静电', conceal: '避雷针'}} ];

Obviously, pokemons have added Pikachu's data, and all data have added property (attribute), type (type), character (characteristic) and the common (normal characteristic) & conceal (hidden characteristic) data under it.

The display interface still does not change the displayed content, but we will display more information in the details interface.

  1. Environment configuration

To use ngRouter, check out the documentation and import the angular-route.js file in html according to the installation instructions :

html <script src="libs/angular-route.js"></script>
And add 'ngRoute' in the module declaration of app.js :
js angular.module('pokemon-app', ['ngRoute'])=

  1. route writing

Since we are going to add ngRouter to jump, index.html will not put the list view, leaving only the title and ngView.

Create a new pokemon folder, and create new view template files pm-list.html and pm-detail.html in the pokemon folder. The current project file view is as follows:
Project file view.jpg

The first thing to learn to write routing must be to read the documentation . Well, installation & example & module components, we must look at the example after installation:
See [$route](https://code.angularjs.org/1.6.9/docs/api/ngRoute/service/$route#examples) for an example of configuring and using ngRoute.
it is so straightforward, just jump over and there is a demo code. . Follow along, learn its js, and create two controllers for the above pm-list & pm-detail. First, pm-list corresponds to PMListController, and pm-detail corresponds to PMDetailController.

Move pokemons&remove in AppController to PMListController. Since the details page will receive the parameters passed by the list display page, add $routeParams to PMDetailController:

```
PMListController.$inject = ['$scope'];
function PMListController ($scope) {
$scope.pokemons = pokemons;
$scope.remove = function (index) {
$scope.pokemons.splice(index, 1);
}
}

PMDetailController.$inject = ['$scope', '$routeParams'];
function PMDetailController ($scope, $routeParams) {}
```

Next, write the routing configuration and clarify the role of the routing configuration. Naturally, it is to connect the link, the view template and the controller to achieve the effect of jumping to a certain interface and calling its controller after entering a certain address, then in Refer to the example in the document just now and start writing:

.config (function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'pokemon/pm-list.html', controller: 'PMListController' }) .when('/pokemon/:no', { templateUrl: 'pokemon/pm-detail.html', controller: 'PMDetailController' }) .otherwise({ redirectTo: '/' }); });

Clearly, does '/' jump to the list view, '/pokemon/:no' jumps to the details view, and if you enter an address that doesn't exist in the routing configuration, it will jump to the '/' address by default.

  1. Interface & business logic writing

Now that we have completed the initialization of the controller and the writing of the routing configuration, the interface and business logic are left.

First put the index.html

The tag and all its sub-elements are cut into pm-list.html without any modification for the time being.
Add ng-view to index.html as follows:
<!DOCTYPE html> <html lang="en" ng-app="pokemon-app"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>口袋妖怪</title> <script src="libs/angular.js"></script> <script src="libs/angular-route.js"></script> <script src="app.js"></script> <link rel="stylesheet" href="app.css"/> </head> <body ng-controller="AppController"> <h1>口袋妖怪管理系统</h1> <div ng-view></div> </body> </html>

So now open index.html and try?
Open html locally and report an error.png

Is there something wrong? Take a look at the error.
console Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https
Cross-origin request support problem, it should be Ajax used in ngRoute, then the solution is very simple, go back to the last extension of the previous article to learn to install http-server, use http-server to open a simple server locally Okay, try it first
http-server runs successfully.png

The operation is successful, then continue, modify the name item in the list view, so that it can be clicked to jump to the details view

<td><a href="/#!/pokemon/{{pokemon.no}}">{{pokemon.name}}</a></td>

Write a detail view:

<p><b>编号: </b>No.{{pokemon.no}}</p>
<p><b>名称: </b>{{pokemon.name}}</p>
<p><b>体重: </b>{{pokemon.weight}}</p>
<p><b>属性: </b>{{pokemon.property}}</p>
<p><b>种类: </b>{{pokemon.type}}</p>
<div>
  <b>特性: </b>
  <ul>
    <li><b>普通特性: </b>{{pokemon.character.common}}</li>
    <li><b>隐藏特性: </b>{{pokemon.character.conceal}}</li>
  </ul>
</div>

<a href="/#!/pockmon">返回列表</a>

Continue to use the http address just now to access (remember to force ctrl+F5 to refresh the cache hehehe)

Now the program can jump from list to detail, but detail has not obtained the selected pokemon object. We get the no passed from the selected pokemon through $routeParams, and print the content of $routeParams:
$routeParam result.png

Ok, no problem is a json object, we select the corresponding pokemon according to the no to pokemon passed by $routeParams

PMDetailController.$inject = ['$scope', '$routeParams'];
    function PMDetailController ($scope, $routeParams) {
        console.log('$routeParams:', $routeParams);
        angular.forEach(pokemons, function (element) {
            if (element.no === $routeParams.no) {
                $scope.pokemon = element;
                console.log('the match pokemon:', $scope.pokemon);
            }
    });
}

Now we go back to the website, refresh and find that the details of the corresponding Pokemon have come out~
Details page.png

The source code of this chapter is the second submission feat(pokemon) under the master branch of Nodreame/pokemon-website : config router & finish pokemon detail with ngRoute .

4. Summary

So far, we have learned the basic use of AngularJS and the basic configuration method of its routing module ngRoute. In the next chapter, we will continue to expand the application based on the current code.

To be continue..

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324770998&siteId=291194637