angularJS中-$route路由-$http(ajax)的使用
后台请求使用的是nodeJS驱动(后面帖代码),很简单的RESTFUL, 页面使用的是bottstarp3.0(懒人神器);
第一个例子:
在本地架设NODEJS, angular的所有请求都是请求本地的3000端口, 这个例子展示的是angular用GET请求服务器的list.json, 1.json, 2.json等文件;
POST请求/0和/id这两个地址:
运行下面代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>angular</title> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <script src="http://cdn.bootcss.com/jquery/2.1.1/jquery.js"></script> <script src="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular.min.js"></script> <link href="http://cdn.bootcss.com/bootstrap/3.3.1/css/bootstrap.css" rel="stylesheet"> <!-- <script src="http://cdn.bootcss.com/underscore.js/1.7.0/underscore-min.js" type="text/javascript"></script> --> <script src="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular-resource.min.js"></script> <script src="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular-route.min.js"></script> </head> <body ng-app="app"> <script type="text/javascript"> var app = angular.module("app",["ngResource",'ngRoute']); </script> <div class="panel panel-default"> <div class="panel-heading"> </div> <div class="panel-body" ng-controller="reso"> <table class="table"> <tr> <td>name</td> <td>age</td> </tr> <tr ng-repeat="i in users"> <td> {{i.name}} </td> <td> {{i.age}} </td> </tr> </table> <button class="btn btn-default" ng-click="update(1)"> query_1.json </button> <button class="btn btn-default" ng-click="update(2)"> query_2.json </button> <button class="btn btn-danger" ng-click="update(0)"> GET_0.json </button> <button class="class btn btn-waring" ng-click="post(0)"> POST_0.json </button> <table class="table"> <tr ng-repeat="i in msgs"> <td class="alert-warning alert"> {{i.id}} </td> </tr> </table> </div> </div> <script type="text/javascript"> //所有的依赖都要在外部定义好; var app = angular.module("app", ["ngResource",'ngRoute']); app.factory('Geek', function($resource) { var url = "http://127.0.0.1:3000"; //直接新建一个REST服务, 相当于提供了一堆请求的合集; return $resource(url + "/:id.json", {}, { query: { method: "GET", params: { id: "list" }, isArray: true }, get : { method : "GET", params : { id : "0" } }, save : { method : "POST", params : { id : "id" } } }); }); app.factory("http",function($http) { var url = "http://127.0.0.1:3000"; return function(search,data) { return $http.post(url+search, data); }; }); function reso($scope, Geek, http, $rootElement) { $scope.users = Geek.query(); //$scope.post = window.root = $rootElement; $scope.post = function(id) { http("/0").then(function(r){ var data = r.data; //var data = JSON.stringify(r.data); //var aEl = angular.element('<div class="alert alert-success" role="alert">'+data+"</div>"); //root.append( aEl ) $scope.msgs = data.list; x = msgs }); //有加了一个请求数据就报了跨域问题,卧槽; //而且请求的方式变成了OPTION,我读书少别逗我啊; http("/0",id).then(function(r){ var data = r.data; }); }; $scope.update = function(id) { Geek.query({ id: id }).$promise.then(function(r) { $scope.users = r; }) }; }; </script> </body> </html>
这个例子的gruntFile.json文件是这样的, 用了nuysoft的Mock, 通过npm install Mockjs,不要忘记了
运行下面代码
{ "name": "nono", "version": "0.0.0", "description": "for watch", "main": "Gruntfile.js", "dependencies": { "grunt": "~0.4.5", "express": "~3.15.2", "grunt-contrib-connect": "~0.6.0", "grunt-contrib-watch": "~0.5.3" }, "devDependencies": {}, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "sqqihao.github.com" }, "keywords": [ "nono" ], "author": "nono", "license": "__MIT__" }
nodejs的文件内容如下(安装nodejs很简单的, 下载以后复制到全局变量即可哦)
运行下面代码
var express = require('express') , http = require('http') , path = require('path'); var Mock = require('mockjs'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); }; app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1') res.header("Content-Type", "application/json;charset=utf-8"); next(); }); app.get('/', function( req, res){ res.setHeader('Content-Type', 'application/json;charset=utf-8'); res.send("you are welcom!"); }); app.get("/list.json",function(req, res) { res.setHeader('Content-Type', 'application/json;charset=utf-8'); res.send([{ name : "nono", age : 26 },{ name : "hehe", age : 24 }]); }); app.get("/0.json",function(req, res) { res.setHeader('Content-Type', 'application/json;charset=utf-8'); res.send([{ name : "youare", age : "welcome" }]); }); app.get("/1.json",function(req, res) { res.setHeader('Content-Type', 'application/json;charset=utf-8'); res.send([{ name : "yy", age : 22 },{ name : "niubiu", age : 50 }]); }); app.get("/2.json",function(req, res) { res.setHeader('Content-Type', 'application/json;charset=utf-8'); res.send([{ name : "ddp", age : 33 },{ name : "makiro", age : 20 }]); }); app.post("/0",function(req, res) { res.setHeader('Content-Type', 'application/json;charset=utf-8'); var data = Mock.mock({ 'list|1-10': [{ 'id|+1': 1 }] }); data.list = Mock.Random.shuffle(data.list); res.send(data); }); app.post("/id",function(req, res) { res.setHeader('Content-Type', 'application/json;charset=utf-8'); res.send("yy"); }); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
第二个例子:
我们在firefox或者是chrome里面一直用console.log 等打log的方法, angular对这些方法进行了简单的封装:
运行下面代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>angular</title> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <script src="http://cdn.bootcss.com/jquery/2.1.1/jquery.js"></script> <script src="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular.min.js"></script> <link href="http://cdn.bootcss.com/bootstrap/3.3.1/css/bootstrap.css" rel="stylesheet"> <!-- <script src="http://cdn.bootcss.com/underscore.js/1.7.0/underscore-min.js" type="text/javascript"></script> --> <!-- <script src="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular-resource.min.js"></script> <script src="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular-route.min.js"></script> --> </head> <body ng-app="app"> <script type="text/javascript"> var app = angular.module("app",[]); </script> <div class="panel panel-default"> <div class="panel-heading"> $log()的使用, 主要用来调试: </div> <div class="panel-body" ng-controller="LogController"> <div class="alert alert-success"> <input class="btn" type="text" ng-model="message"/> <button class="btn btn-danger" ng-click="$log.log(message)">log</button> <button class="btn btn-danger" ng-click="$log.warn(message)">warn</button> <button class="btn btn-danger" ng-click="$log.info(message)">info</button> <button class="btn btn-danger" ng-click="$log.error(message)">error</button> </div> </div> <script type="text/javascript"> app.controller('LogController', ['$scope', '$log', function($scope, $log) { $scope.$log = $log; $scope.message = 'Hello World!'; }]); </script> </div> </body> </html>
例子3:
angular的路由处理, ng-view的使用, 所有对应路由的模板会在 标志有ng-view属性的div中显示. 我们通过url控制页面对应的逻辑是个好主意么么哒;
运行下面代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>angular</title> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <script src="http://cdn.bootcss.com/jquery/2.1.1/jquery.js"></script> <script src="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular.min.js"></script> <link href="http://cdn.bootcss.com/bootstrap/3.3.1/css/bootstrap.css" rel="stylesheet"> <!----> <script src="http://cdn.bootcss.com/underscore.js/1.7.0/underscore-min.js" type="text/javascript"></script> <script src="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular-resource.min.js"></script> <script src="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular-route.min.js"></script> </head> <body ng-app="app"> <script type="text/javascript"> var app = angular.module("app",['ngRoute']); </script> <!--使用angular的路由处理--> <div class="panel panel-default"> <div class="panel-heading"> ng-view的实例 </div> <div class="panel-body" ng-controller="route"> <ul class="nav nav-pills" role="tablist" > <li role="presentation" ng-repeat="id in [1, 2, 3 ]"> <a href="#/list/{{ id }}"> ID{{ id }}</a> </li> </ul> <div ng-view></div> </div> </div> <script type="text/javascript"> app.controller("route",function(){}); //app.controller("hehe", ); //路由是定义在app的config里面的; app.config(function($routeProvider, $locationProvider) { console.log($routeProvider); /* app.controller("hehe", function($scope, $routeParams) { $scope.ver = $routeParams.bookId //$scope }); */ $routeProvider.when('/list/:bookId', { template: '<div>This is in page : <a href="#/list/{{ver}}/detail">href-to-{{ver}}</a></div>', controller : function($scope, $routeParams) { $scope.ver = $routeParams.bookId } }) .when('/list/:bookId/detail', { template : "<div>this is detail : {{bookId}}</div><a href='#/list/{{bookId}}'>back</a>", controller : function($scope, $routeParams) { console.log( $routeParams ) $scope.bookId = $routeParams.bookId; } }) //剩下的走这路由 .otherwise; }) </script> </body> </html>
天道酬勤