Angularjs calls Web APIs and angularjs calls APIs
This morning I share an article "Create Web API and use" http://www.cnblogs.com/insus/p/7771428.html next, I will share another article, how to call Web API in angularjs.
Define a mode:
Using System; using System. collections. generic; using System. linq; using System. web; namespace Insus. NET. models {public class GarbageClassification {private string _ ClassificationName; public string ClassificationName {get {return _ ClassificationName;} set {_ ClassificationName = value ;}}}}Source Code
Add an object class:
Using System; using System. collections. generic; using System. linq; using System. web; using Insus. NET. models; namespace Insus. NET. entities {public class DataEntity {public List <GarbageClassification> GetDatas () {return new List <attributes> () {new GarbageClassification () {ClassificationName = "Waste Paper"}, new GarbageClassification () {ClassificationName = "plastic"}, new GarbageClassification () {ClassificationName = "Glass"}, new GarbageClassification () {ClassificationName = "metallic"}, new GarbageClassification () {ClassificationName = "fabric "}};}}}Source Code
If your data comes from a database, you need to modify the entity class, modify the code, and read data from the database.
Now, we need to create a Web API:
Using System; using System. collections. generic; using System. linq; using System. net; using System. net. http; using System. web. http; using Insus. NET. models; using Insus. NET. entities; namespace Insus. NET. apis {public class GarbageApiController: ApiController {[Route ("api/GarbageApi/GetClassifications")] [HttpPost] public List <criteria> GetClassifications () {DataEntity de = new DataEntity (); return de. getDatas ();}}}Source Code
OK, model, Entity, and API are all ready. The following shows how to use angularjs on the front end to call the previously written API.
Html:
Angularjs code is similar to jQuery's ajax call:
Var oApp = angular. module ('garbageapp', []) oApp. controller ('garbagectrl', function ($ scope, $ http) {var obj ={}; $ http ({method: 'post', url: '/api/GarbageApi/GetClassifications', ype: 'json', headers: {'content-type': 'application/json; charset = UTF-8 '}, data: json. stringify (obj ),}). then (function (response) {$ scope. classifications = response. data ;});});Source Code
Demo (running result ):