This is the seventh chapter of the "angularjs– seven-step from rookie to expert" series.
In the first article, we showed how to start building a ANGULARAJS application. In the fourth to fifth chapter we discuss the angular built-in directives, the last one that understands the power of services.
In this chapter, we take a look at some of the key points that we didn't have a chance to elaborate on, and at the end of the article we'll list some great links and tools for learning resources.
Through this entire series of tutorials, we will develop an audio player for NPR (National Public Radio), which will display the latest stories that are now aired on the Morning edition program and play them in our browser. Complete version of the demo can be seen here.
7. Routing
In single-page applications, jumps between views are especially important, and as applications become more complex, we need a way to precisely control when and how the page is presented to the user.
We can support different page transitions by introducing different templates to the main page, but the downside is that more and more embedded code leads to the final difficulty of managing.
With the Ng-include directive we can integrate many templates into the view, but we have a better way to deal with this situation, we can break the view into layout and template view, and then display the desired view according to the specific URL that the user accesses.
We can stitch these "fragments" together in a layout template.
Angularjs the idea by declaring routes on the $routeprovider (provider of $route service)
Using $routeprovider, we can make better use of the browsing History API and allow users to save the current path to a bookmark for later use
To set up routing in our application, we need to do two things: first, we need to point out where we store the layout template that will store the content of the new page. For example, if we want to have headers and footer on all pages, we can design a layout template like this:
123456789 |
<
header
>
<
h1
>Header</
h1
>
</
header
>
<
div class
=
"content"
>
<
div ng-view></
div
>
</
div
>
<
footer
>
<
h5
>Footer</
h5
>
</
footer
>
|
Ng-view instructions where to render the template at high speed $routeprovider
Second, we need to configure our routing information and we will configure the $routeprovider in the application
$routeProvider provides two ways to handle routing: when and otherwise. When the method receives two parameters, the first setting $location.path (). (Direct use of "//" also no problem)
The second parameter is the configuration object, which can contain different keys, and we can simply say a few
Controller
12345 |
controller: ‘MyController‘ // or controller: function ($scope) { // ... } |
If the Controller property is set in the Configuration object, the controller is instantiated when the route is loaded, which can be a string (a controller that must be registered in the module) or a controller function
Template templates
If we set a value on the template property of the configuration object, then it will be rendered to the Ng-view in the DOM.
Templateurl
1 |
templateUrl: ‘views/template_name.html‘ |
If we set the value in the Templateurl property of the Configuration object, Angularjs will get the template through XHR and render the template content to Ng-view in the DOM
It is worth noting that the Templateurl property is the same as the process of other ANGULARJS XHR requests, that is, even if the user leaves from this page, and so he returns to this page, the application will not request this template page, because $ Templatecache has cached this template.
Add some routes
12345678 |
angular.module(
‘myApp‘
, []).
config([
‘$routeProvider‘
,
function
($routeProvider) {
$routeProvider.when(
‘/‘
, {
controller:
‘HomeController‘
,
template:
‘
})
.otherwise({redirectTo:
‘/‘
});
}]);
|
$routeProvider can also handle the arguments passed in the URL (for example,/PEOPLE/42, assuming that 42 is the ID number of the people we are looking for) simply precede the string with ': ', $ Routeprovider will try to match the ID in the URL and use the ID as key in the $routeparams service
1234 |
$routeProvider.when( ‘/person/:id‘ , { controller: ‘PeopleController‘ , template: ‘<div>Person show page: {{ name }}</div>‘ }) |
In Peoplecontroller, we retrieve the ID of the people specified in the route:
12345 |
app.controller( ‘PeopleController‘ , function ($scope, $routeParams) { // We now have access to the $routeParams // At the route /person/42, our $routeParams will look like: // { id: 42 } }); |
Filter filters
In the Angularjs world, Filter provides a way to format data, angular also provides us with a lot of built-in filters, and creating custom filters is fairly straightforward.
In the template binding of HTML {{}}, we use | To invoke the filter, for example, we want the string to display all uppercase characters:
Of course, we can also use the $filter service in JavaScript to invoke the filter, and take the string capitalization for example:
12345 |
app.controller ( ' Democontroller ' Code class= "ACTIONSCRIPT3 string" > ' $scope ' , ' $filter ' &NBSP;&NBSP; function ($scope, $filter) { $scope. Name = $filter ( ' lowercase ' ) ( ' Ari ' |
How do I pass parameters to filter? Just put the parameter after the filter, with a colon in the middle (if there are multiple arguments to pass, with a colon after each parameter) for example, a digital filter can help us limit the number of digits, if you want to display two decimal places, plus number:2.
1 |
{{ 123.456789 | number: 2 }} |
See it
123.46
We can use n multiple filters at the same time, we can see how to use multiple filters at the same time when we build a custom filter, and before that we continue to look at a couple of angular's own filters.
Currency
Currency filter is mainly to format the number into a currency, meaning that 123 after the format of the $123.00
Currency can select the appropriate currency symbol as needed. The default is to convert based on the locale of the current operating system.
Date
Date filter is mainly based on the format we provide to format the date, he provides a lot of built-in options, if not specified format, the default display mediumdate form
Here are some of our own date formats, which we can use to create custom date formats by combining different formatting options
Filter
The filter filter is used primarily to filter an array of data and return a new array containing the data of the sub-array
For example, when the client searches, we can quickly filter out the results we want from the array.
This filter method receives a string,object, or the function parameter is used to select/move the array element
If The first parameter passed in is a: |
String |
Receive the element that matches this string, if you want to exclude certain strings, add '! ' to the front. It's all right. |
Object |
If only one string is passed, a similar substring match is made as the property name of the object, and if you want to match all the attributes, use ' $ ' as the key |
Function |
This function is executed for each element in the array, and the resulting results are placed in a new array |
can also pass a second parameter into the filter method that would be used to determine if the expected value and the A Ctual you can also pass in the second argument to the filter method, which he uses to determine if the expected and actual values are considered to match the problem
If The second parameter passed in are: |
True |
Perform a strict match comparison (as with ' angular.equals (expected,actual) ') |
False |
Perform case-sensitive substring matching |
Function |
Executes the function and accepts an element, provided that the return result of the function is true |
See it
The iscapitalized function is as follows:
12 |
$scope.isCapitalized = function (str) { return str[ 0 ] == str[ 0 ].toUpperCase(); } |
Json
The JSON filter receives JSON or JavaScript objects and then converts them into strings, which is useful when debugging a program! Translator feel: Mother no longer have to worry about my debug, convenient and heinous
LimitTo
The LimitTo filter generates a new array or string based on the passed parameter values, the parameter value is an integer, is truncated from the beginning, the parameter is negative, and the last intercept
Returns the entire array or string if the qualified value exceeds the length of the string
See it
lowercase
Lowercase filter is obvious, the entire string is programmed in lowercase form
See it
lowercase string
1 |
{{ "San Francisco is often cloudy" | lowercase }} san francisco is often cloudy |
Number
The number filter formats the text as a number, optionally accepting the argument (optional) to determine the digits of the number after formatting
If the argument is non-numeric, an empty string is returned
See it
Simple numeric formatting
1 |
{{ 1234567890 | number }} 1 , 234 , 567 , 890 |
Format numbers to one decimal
1 |
{{ 1.234567 | number: 1 }} 1.2 |
By
The order-by filter is primarily sorted by the given expression array
The order by function can accept two parameters: the first one must be provided, the second is an optional parameter
The first parameter determines how the array is sorted
If the first parameter passed in is: |
function |
The ' Getter ' function that will be used as the object |
String |
Strings are sorted as keys to array elements, and you can also pass in ' + ' or '-' to determine whether ascending or descending |
Array |
The elements in this array are used as the basis for sorting expressions, and elements that use the result of the first non-strict equality expression are used as the basis for judging other elements. |
The second parameter controls the sort order of the array (either reversed or not).
See it
Sort by name
Uppercase
Uppercase filter is the whole string into uppercase form
See it
1 |
{{ "San Francisco is often cloudy" | uppercase }} SAN FRANCISCO IS OFTEN CLOUDY |
Create a custom filter
As we saw earlier, creating a custom filter is fairly straightforward, and we just have to configure it to our module, so let's create a first-letter capitalization filter.
First, we create a module
1234 |
angular.module( ‘myApp.filters‘ , []) .filter( ‘capitalize‘ , function () { return function (input) {} }); |
Fliters is actually a function, receive input string, we can do some error check in the function
12345678 |
angular.module(
‘myApp.filters‘
, [])
.filter(
‘capitalize‘
,
function
() {
return function
(input) {
// input will be ginger in the usage below
if (input)
return input[
0
].toUpperCase() + input.slice(
1
);
}
});
|
See it
There are some topics that we haven't had time to discuss.
In this series of tutorials, we introduced a lot of things that can make you easy to get started with Angularjs, of course, there are many points no opportunity to talk about, are listed below, hoping to have the opportunity to study with his family
- Promises (can make multiple asynchronous requests more organized)
- Building Custom Directives (customized directive)
- $resource Service ($resource service, very useful one, the bottom is called $http service)
- Units Testing (unit test, this is particularly important, can even be taken out in terms of many, recommended Jasmine)
- End-to-end Testing (IBID.)
- Midway testing (test in front of both)
- i18n and i10n language translation/localization (multi-lingual)
- Authentication and customizing XHR requests (authentication and custom XHR requests)
- Using the $provide service to build customizable services (use the $provider service to create custom services)
- Forms and validations (forms and validation)
- ie compatibility (ie compatibility)
Finally, if you like our series of tutorials, just as we are trying to create a book, this book discusses all the topics listed above, more information please visit ng-book.com
Here is a sample of Ng-book, free of charge Oh! Just leave your email address and we'll send a sample to your Inbox.
List of learning resources
For more and deeper knowledge about ANGULARJS please visit the following sites:
- Egghead.io
- Google + Community
- Dan Wahlin ' s blog
- Joel Hooks ' s blog
- Dean Sofer ' s blog
- Yearofmoo.com
Here are some interesting angular programs for everyone to play with
- Angular-app
- Ng-boilerplace
- The very awesome lineman project
- Angular-ui
- Angular-bootstrap
[Study notes] Seven steps from ANGULARJS rookie to expert (7): Routing [Turn]