angular的跨域(angular百度下拉提示模拟)和angular选项卡

时间:2022-10-26 05:08:04

1.angular中$http的服务:

  $http.get(url,{params:{参数}}).success().error();

  $http.post(url,{params:{参数}}).success().error();

  $http.jsonp(url,{params:{wd:'',cb:'JSON_CALLBACK'}}).success().error();

  注意jsonp中cb在angular中规定只能使用JSON_CALLBACK

  $watch(谁,做什么,false);

  谁指的是需要监听谁,做什么指的是在监听对象发生改变的时候会触发的函数,最后一个参数布尔值,true表示深度监视,比如监听的是对象arr,在arr中的每一项发生改变的时候都会触发函数,true还表示可以监听多个,如果默认false的话,只能监听单个对象。

下面使用angular的jsonp来做了一个简单百度搜索下拉,原生的百度搜索下来再前面的文章中写过,有兴趣的可以搜一下看看

<!doctype html>
<html ng-app="text">
<head>
<meta charset="utf-8">
<title>angular百度下拉搜索</title>
<script src="angular.min.js"></script>
<script>
var app=angular.module('text',[]); app.controller('cont',['$scope','$http',function($scope,$http){
$scope.arr=[];
//提前初始化数据,这里给一个初始值,否则刷新页面angular的脏检查会认为是失败
$scope.str='';
//注意在angular中不能使用angular以外的方法,例如这里使用jquery的$.ajax或者$.getScript会出现问题
$scope.$watch('str',function(){
$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{params:{
wd:$scope.str,
//angular规定cb必须是用"JSON_CALLBACK"
cb:'JSON_CALLBACK'
}}).success(function(json){
$scope.arr=json.s;
}).error(function(){
alert('失败了');
});
});
}]);
</script>
</head> <body>
<div ng-controller="cont">
<input type="text" ng-model="str"/>
<ul>
<li ng-repeat="s in arr">{{s}}</li>
</ul>
</div>
</body>
</html>

  

2.angular的选项卡,自己认为选项卡虽然简单,但是透过选项卡能展现很多东西的思路,这个angular的选项卡还是很简单的

<!doctype html>
<html ng-app="text">
<head>
<meta charset="utf-8">
<title>angular选项卡</title>
<script src="angular.js"></script>
<style>
*{
padding:0;
margin:0;
}
p{
width:100px;
height:100px;
background:#ccc;
border:1px solid #000;
}
.active{
background:skyblue;
}
input{
background:#333;
color:#fff;
}
</style>
<script>
var app=angular.module('text',[]);
app.controller('cont1',['$scope',function($scope){
//利用$scope.now来控制div的显示和隐藏
$scope.now=0;
$scope.arr=[
{name:"音乐",content:"BEYOND不朽"},
{name:"体育",content:"C罗是垃圾"},
{name:"新闻",content:"物价还在上涨"},
];
//挂载一个函数过渡一下,解决ng-repeat和ng-事件同时出现的问题
$scope.fn=function(n){
$scope.now=n;
};
}]);
</script>
</head> <body>
<div ng-controller="cont1">
<!--注意在angular中ng-repeat和ng-事件同时出现会出现问题,解决办法是在$scope下挂载的函数中过渡一下-->
<input ng-repeat="json in arr" type="button" value="{{json.name}}" ng-class="now==$index?'active':''" ng-click="fn($index)" />
<p ng-repeat="json in arr" ng-show="now==$index">{{json.content}}</p>
</div>
</body>
</html>