angularJS中-$route路由-$http(ajax)的使用

前端之家收集整理的这篇文章主要介绍了angularJS中-$route路由-$http(ajax)的使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

后台请求使用的是nodeJS驱动(后面帖代码),很简单的RESTFUL,页面使用的是bottstarp3.0(懒人神器);

  第一个例子:

  在本地架设NODEJS,angular的所有请求都是请求本地的3000端口,这个例子展示的是angular用GET请求服务器的list.json,1.json,2.json等文件;

  POST请求/0和/id这两个地址:

运行下面代码

复制代码

<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<Metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>angular</title>
  <Metahttp-equiv="X-UA-Compatible"content="IE=edge,chrome=1">
<scriptsrc="http://cdn.bootcss.com/jquery/2.1.1/jquery.js"></script>
<scriptsrc="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular.min.js"></script>
<linkhref="http://cdn.bootcss.com/bootstrap/3.3.1/css/bootstrap.css"rel="stylesheet">
<!--
<scriptsrc="http://cdn.bootcss.com/underscore.js/1.7.0/underscore-min.js"type="text/javascript"></script>
-->
<scriptsrc="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular-resource.min.js"></script>
<scriptsrc="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular-route.min.js"></script>

</head>
<bodyng-app="app">
<scripttype="text/javascript">varapp=angular.module("app",["ngResource",'ngRoute']);</script>

<divclass="panelpanel-default">
<divclass="panel-heading">

</div>
<divclass="panel-body"ng-controller="reso">
<tableclass="table">
<tr>
<td>name</td>
<td>age</td>
</tr>
<trng-repeat="iinusers">
<td>{{i.name}}</td>
<td>{{i.age}}</td>
</tr>
</table>
<buttonclass="btnbtn-default"ng-click="update(1)">
query_1.json</button>
<buttonclass="btnbtn-default"ng-click="update(2)">
query_2.json</button>
<buttonclass="btnbtn-danger"ng-click="update(0)">
GET_0.json</button>
<buttonclass="classbtnbtn-waring"ng-click="post(0)">
POST_0.json</button>
<tableclass="table">
<trng-repeat="iinmsgs">
<tdclass="alert-warningalert">{{i.id}}</td>
</tr>
</table>
</div>
</div>
<scripttype="text/javascript">//所有的依赖都要在外部定义好;
varapp=angular.module("app",'ngRoute']);
app.factory('Geek',function($resource){varurl="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){varurl="http://127.0.0.1:3000";returnfunction(search,data){return$http.post(url+search,data);
};
});functionreso($scope,Geek,http,$rootElement){
$scope.users=Geek.query();//$scope.post=
window.root=$rootElement;
$scope.post=function(id){
http("/0").then(function(r){vardata=r.data;//vardata=JSON.stringify(r.data);
//varaEl=angular.element('<divclass="alertalert-success"role="alert">'+data+"</div>");
//root.append(aEl)
$scope.msgs=data.list;
x=msgs
});//有加了一个请求数据就报了跨域问题,卧槽;
//而且请求的方式变成了OPTION,我读书少别逗我啊;
http("/0",id).then(function(r){vardata=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,不要忘记了

复制<a href=代码" style="margin:0px;float:left;border:none;" src="http://common.cnblogs.com/images/copycode.gif">

{"name":"nono","version":"0.0.0","description":"forwatch","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:notestspecified\"&&exit1"
},"repository":{"type":"git","url":"sqqihao.github.com"
},"keywords":["nono"
],"author":"nono","license":"__MIT__"}

  nodejs的文件内容如下(安装nodejs很简单的,下载以后复制到全局变量即可哦)

复制代码

varexpress=require('express'),http=require('http'),path=require('path');varMock=require('mockjs');varapp=express();//allenvironmentsapp.set('port',process.env.PORT||3000);
app.set('views',__dirname+'/views');
app.set('viewengine','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')));//developmentonlyif('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('/',res){
res.setHeader('Content-Type','application/json;charset=utf-8');
res.send("youarewelcom!");
});

app.get("/list.json",'application/json;charset=utf-8');
res.send([{
name:"nono",age:26
},{
name:"hehe",age:24
}]);
});


app.get("/0.json",'application/json;charset=utf-8');
res.send([{
name:"youare",age:"welcome"
}]);
});


app.get("/1.json",'application/json;charset=utf-8');
res.send([{
name:"yy",age:22
},{
name:"niubiu",age:50
}]);
});

app.get("/2.json",'application/json;charset=utf-8');
res.send([{
name:"ddp",age:33
},{
name:"makiro",age:20
}]);
});

app.post("/0",'application/json;charset=utf-8');vardata=Mock.mock({'list|1-10':[{'id|+1':1
}]
});
data.list=Mock.Random.shuffle(data.list);
res.send(data);
});

app.post("/id",'application/json;charset=utf-8');
res.send("yy");
});

http.createServer(app).listen(app.get('port'),function(){
console.log('Expressserverlisteningonport'+app.get('port'));
});

第二个例子:  

我们在firefox或者是chrome里面一直用console.log 等打log的方法,angular对这些方法进行了简单的封装:

  

score.js/1.7.0/underscore-min.js"type="text/javascript"></script> --> <!-- <scriptsrc="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular-resource.min.js"></script> <scriptsrc="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular-route.min.js"></script> --> </head> <bodyng-app="app"> <scripttype="text/javascript">varapp=angular.module("app",[]);</script> <divclass="panelpanel-default"> <divclass="panel-heading"> $log()的使用,主要用来调试:</div> <divclass="panel-body"ng-controller="LogController"> <divclass="alertalert-success"> <inputclass="btn"type="text"ng-model="message"/> <buttonclass="btnbtn-danger"ng-click="$log.log(message)">log</button> <buttonclass="btnbtn-danger"ng-click="$log.warn(message)">warn</button> <buttonclass="btnbtn-danger"ng-click="$log.info(message)">info</button> <buttonclass="btnbtn-danger"ng-click="$log.error(message)">error</button> </div> </div> <scripttype="text/javascript"> app.controller('LogController',['$scope','$log',function($scope,$log){ $scope.$log=$log; $scope.message='HelloWorld!'; }]);</script> </div> </body> </html>

例子3:


angular的路由处理,ng-view的使用,所有对应路由的模板会在 标志有ng-view属性的div中显示. 我们通过url控制页面对应的逻辑是个好主意么么哒;

score.js/1.7.0/underscore-min.js"type="text/javascript"></script> <scriptsrc="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular-resource.min.js"></script> <scriptsrc="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular-route.min.js"></script> </head> <bodyng-app="app"> <scripttype="text/javascript">varapp=angular.module("app",['ngRoute']);</script> <!--使用angular的路由处理--> <divclass="panelpanel-default"> <divclass="panel-heading"> ng-view的实例</div> <divclass="panel-body"ng-controller="route"> <ulclass="navnav-pills"role="tablist"> <lirole="presentation"ng-repeat="idin[1,2,3]"> <ahref="#/list/{{id}}">ID{{id}}</a> </li> </ul> <divng-view></div> </div> </div> <scripttype="text/javascript"> app.controller("route",function(){});//app.controller("hehe",); //路由是定义在app的config里面的; app.config(function($routeProvider,$locationProvider){ console.log($routeProvider);/* app.controller("hehe",$routeParams){ $scope.ver=$routeParams.bookId //$scope });*/ $routeProvider.when('/list/:bookId',{ template:'<div>Thisisinpage:<ahref="#/list/{{ver}}/detail">href-to-{{ver}}</a></div>',controller:function($scope,$routeParams){ $scope.ver=$routeParams.bookId } }) .when('/list/:bookId/detail',{ template:"<div>thisisdetail:{{bookId}}</div><ahref='#/list/{{bookId}}'>back</a>",$routeParams){ console.log($routeParams) $scope.bookId=$routeParams.bookId; } })//剩下的走这路由.otherwise; })</script> </body> </html>

复制代码

猜你在找的Angularjs相关文章