Tutorial _ AngularJS

Source: Internet
Author: User
Tags tojson
This article mainly introduces the use of Angular. js makes a simple RSS reader tutorial. AngularJS is a very popular JavaScript library. The production method described in this article mainly uses the FreedReadR template. For more information, see Introduction

A few years ago, I wrote an RSS reader using C #, but I thought it would be better if I made it into a SPA (single-page application. Angular makes some things simple, and RSS reader is one of them. I also used Twitter Bootstrap (UI) to implement the RSS reader. debugging page styles is one of the most difficult parts... maybe it is because I am not good at css.

Background

I have some favorite websites (CodeProject, Dr. Dobb's Journal, ComputerWorld, Inc. Magazine ). However, I found that many websites have annoying advertisements and bad la S. I really don't want to see these things. When I say this, it does not include the CodeProject website.


Switching between these websites wastes a lot of time. Therefore, I prefer to browse the article title and introduction so that I can decide whether to enter the article content page. This is why I decided to write the FreedReadR single-page application.

FreedReadR responds quickly because it reads a small amount of data (RSS source.

Click the CodeProject option below:

The following shows how FreedReadR loads the data of a Website:

Now you can try the following:

Http://newtonsaber.com/FreedReadR

I almost forgot. I searched for this idea on Google before creating my own RSS Reader and found a good piece of code in jsfiddle: angularJS Feed Reader alt.


My code is similar to its code, but it is still different, because I want to implement more functions. FreedReadR allows you to locally store your own RSS source data, so that you can always use applications to create custom RSS sources. In addition, its code is based on Twitter Bootstrap 2 and FreedReadR is based on the new version of Twitter Bootstrap 3.
Use Code

If you are familiar with Angular, there are not many codes in the Development era. Most of the difficulties are the use of Bootstrap in Angular.

You can find a solution to other problems in Angular programming ideas. The usage of $ scope is a little different from that of the controller. First, you must set the application scope in html. Similar to the following code using ng-app = "FreedReadR", the $ scope in html is set: all objects in p labels -- in the following example, the scope is the entire page. I only need a controller to process the entire application logic. I am satisfied with this.

 

RSS Feed Reader using AngularJS


In the preceding html code, you can see that the name of the Angular application template is FreedReadR. When I set the Application Template and add the controller (FeedCtrl) code, I used the same name in the main. js file. Let's take a look at the code for setting parameters in main. js.

var app = angular.module('FreedReadR', []); app.factory('FeedService',function($http){ return {  parseFeed : function(url){   return $http.jsonp('//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=50&callback=JSON_CALLBACK&q=' + encodeURIComponent(url));  } }}); app.controller("FeedCtrl", ['$scope','FeedService', FeedCtrl]);

In the preceding js Code, the first line is to create an AngularJS application template. Note that its name is FreedReadR. We use the same name in html code to reference this template.

Next, we create an Angular factory class, which will be used later to access the RSS source URL to obtain real source data. Take a closer look at the $ http. jsonp Request Used in the code. The URL format is as follows:

//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=50&callback=JSON_CALLBACK&q=

The Google API is called in the URL. I didn't know the Google API before. This is the main code of the jsfiddle example I mentioned at the beginning of the article. To learn more about Google APIs, download https://developers.google.com/feed/v1/jsondevguide.

In the above js Code, you will find that we have called the encodeURIComponent function, which is used to convert URLs.
Configure Angular Controller

The controller is used to process the logic of the application, so most js functions should be in the controller. This is how Angular helps you organize (chaotic) js Code. Did I say it out loud?


Okay, JavaScript encourages disorder, isn't it? This is a bad thing. When talking about the global variables of JavaScript, do you not have to scream with fear? If you don't need it, we may want to revoke your developer license. You have a license to write software, aren't you? (Translator's note: because you have a developer license, you naturally yell at the "global variables" of JavaScript with fear-here is an exaggerated saying, it is intended to explain that developers should be cautious about using global variables in JavaScript .)

Now, let's look at the functions provided by the Controller when we get to know what the application has done. Let's look at every function in the Controller to understand what FreedReadR can do.
Check localStorage. If yes, load

One thing I want to do is to save your source in slocalStorage in the browser. I don't want to mess up the database, but I want you to add custom sources and keep them available in your browser.

LocalStorage restrictions

Of course, the limit of localStorage is that it exists in a given domain name of a specific browser.

This means that if you are from the slave.

For me, this version of the application is OK. because it is what I want, start with a technology that is very fast and knowledgeable about its limitations. the modification restriction may be another article in the future.


You will find that in the Controller code, I first called a function: retrieveFromLocalStorage ().

The function is as follows:

function retrieveFromLocalStorage() {  $scope.allFeeds = [];  console.log("retrieving localStorage...");  try  {  $scope.allFeeds = JSON.parse(localStorage["feeds"]);  console.log($scope.allFeeds.length);   // console.log(JSON.stringify($scope.allFeeds));  if ($scope.allFeeds === null)  {   console.log("couldn't retrieve feeds" );   loadDefaultFeeds();  }  }  catch (ex)  {  console.log("ex: " + ex);  loadDefaultFeeds();  saveToLocalStorage($scope.allFeeds);  }   }

This is a very simple function. It defines an array variable named allFeeds in the scope of $ scope. Then, read a feeds object from the localStorage Array Using the JSON. parse method. This object stores an existing RSS source. If the feeds object is undefined (this is the first time an application is running), the program throws an exception. When an exception is thrown, the application loads some default RSS sources (loadDefaultFeeds () and saves these sources to localStorage for the next use.


Let's first look at the loaddefafefeeds () function, and then let's look at the saveToLocalStorage () function.

function loadDefaultFeeds(){ $scope.allFeeds = [{titleText:"Load (from textbox)",url:""}, {titleText:"CodeProject C#",url:"http://www.codeproject.com/webservices/articlerss.aspx?cat=3"}, {titleText:"ComputerWorld - News",url:"http://www.computerworld.com/index.rss"}, {titleText:"Dr. Dobb's",url:"http://www.drdobbs.com/rss/all"}, {titleText:"InfoWorld Today's News",url:"http://www.infoworld.com/news/feed"}, {titleText:"Inc. Magazine",url:"http://www.inc.com/rss/homepage.xml"}, {titleText:"TechCrunch",url:"http://feeds.feedburner.com/TechCrunch"}, {titleText:"CNN",url:"http://rss.cnn.com/rss/cnn_topstories.rss"}     ];}

As you can see, I have added some of my favorite sources, so that you can easily try this application. it is just an array of objects, defined by titleText and url.

As long as they are all loaded into the $ scope type variables allFeeds, you can use ng-repeat to get them from HTML. It looks like the following:

  • {{feed.titleText}}
  • This creates a list of options. When you click the drop-down box, they will be displayed on the list. as you can see, We reference the allFeeds $ scope variable in the ng-repeat statement, and then we reference the feed. titleText to generate entries.


    Now your button has loaded a good title.

    I said that I will introduce the saveToLocalStorage () method to you. Now let's take a look.

    function saveToLocalStorage(feeds) {  // Put the object into storage   localStorage.setItem('feeds', angular.toJson(feeds));  console.log(angular.toJson(feeds));  console.log("wrote feeds to localStorage"); }

    This is a very simple method. Method allows you to pass in a feeds object (this should be an array of feed objects ). Then we simply call the localStorage. setItem () method. As the method name says, we can use this method to save objects. Note that when we save an object, we call the angular. toJson () method of the object. This method will help us remove some angular attributes that we don't want to save. Therefore, it is very important to call this method, because angular will save some special attributes in the object, and these attributes will confuse you.

    Now, the application has loaded some default RSS sources. If you want to obtain the data of an RSS source, click the drop-down box and select a value, then the application runs the following code to obtain the relevant data. We add a loadFeed function in the $ scope. The function is as follows. The following function is called because the event ng-click = "loadFeed ($ event, feed. url);" is bound to the button in html );".


    LoadFeed = function (e, url) {$ scope. currentButtonText = angular.element(e.tar get ). text (); // clear the last displayed information in the filter text box. // when we select a New RSS source, it may be confusing if we do not clear it. $ scope. filterText = ""; console. log ("loadFeed/click event fired"); if ($ scope. currentButtonText = $ scope. allFeeds [0]. titleText) {// console. log ($ scope. feedSrc); url = $ scope. feedSrc;} $ scope. feedSrc = url; if (url = undefined | url = "") {$ scope. phMessage = "Please enter a valid Feed URL & try again. "; return;} console. log ("button text:" + angular.element(e.tar get ). text (); console. log ("value of url:"); console. log (url); FeedService. parseFeed (url ). then (function (res) {javasscope.loadbutontext=angular.element(e.tar get ). text (); $ scope. feeds = res. data. responseData. feed. entries ;});}

    When you click an event to call the above function, we first determine whether the user selected information is the same as the first option "Load (from textbox)" in the drop-down box. This is done to determine whether the user wants to load the RSS feed provided in the text box. If so, when we call the FeedService. parseFeed method, we directly input the URL value in the text box. If this is not the case, we obtain the URL from the relevant source object.

    Result List

    When the source information is returned, the HTML code uses another ng-repeat to iterate over each item and display them in a friendly format. The HTML code looks like the following:

     
     
      0">{{(feeds | filter:filterText).length}} Items
    • {{feed.title}} {{feed.publishedDate}}

      {{feed.contentSnippet}}

    HTML also creates a friend tag to display the number of obtained text links.
    Search results

    It also displays a search text box that can be used to input text and filter the drop-down list based on the content of the text link.
    Click the link to load data on a new page.

    Finally, if you click a link, it will be loaded on the new page or window of the browser, which makes this tool easy to use.

    Save New Source

    This part is simple, because I completed this application only for my own use.

    If you enter a URL in the text box and click the Save button (down arrow icon), you will see a JavaScript prompt box that looks like the image shown below:

    You can enter the title (it will be displayed in the drop-down list) to identify the new source, and then click OK.

    As long as you do this, this item will be added to the drop-down list. This process is implemented by adding this item to the allFeeds object, and this item will be saved to localStorage immediately.

    This is all content.

    I hope you like this tool like me, which saves a lot of time.

    Release prompt

    Note that the links to many external libraries are CDN. In addition to the Bootstrap files downloaded, other downloaded files are stored in a 3 rdPartyLibs (third-party library) directory. You can download, decompress, and run the code.
    Preparing Web servers for local storage is required

    You must run a web server to make it work normally. Note that the downloaded file contains a small and exquisite web Server (mongoose web serverpattern and configuration file. For this reason, if you want to use logging, you can double-click mongoose.exe and it starts to run. Then, you can simply load: http: // localhost: 999/FreedReadR/it runs on your computer.

    The last one should be noted: What is the [X] button?

    What is the [X] button next to the Save button? That button allows you to release all feedback from your localStorage. If you click it, they will be removed. Localstorage entries named as feedback are simply destroyed, so be careful with them. If you use this button before adding any feedback, there is no problem, otherwise you will lose the feedback you have added.

    I am very lazy. I only use it for my testing. You should still remove it. Laziness is really a sign of great developers.

    Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.