JSONP使用方法
$http.jsonp("http://wthrcdn.etouch.cn/weather_mini?callback=JSON_CALLBACK&city=北京")
.then(function successCallback(response) {
console.log(JSON.stringify(response));
}, function errorCallback(response) {
console.log(JSON.stringify(response));
});
自建服務(wù)
有的時(shí)候我們需要建立自己的服務(wù),而不是每次都在controller里面進(jìn)行$http請求
自己的service不能以$開頭,并且也可以注入controller,但是要放在最后一個
var myServiceApp = angular.module("MyServiceApp", []);
myServiceApp.factory('userListService', ['$http',
function($http) {
var doRequest = function(username, path) {
return $http({
method: 'GET',
url: 'users.json'
});
}
return {
userList: function(username) {
return doRequest(username, 'userList');
}
};
}
]);
$scope上面有一個$watch的方法 它可以監(jiān)控?cái)?shù)據(jù)模型的變化
myServiceApp.controller('ServiceController', ['$scope', '$timeout', 'userListService',
function($scope, $timeout, userListService) {
var timeout;
$scope.$watch('username', function(newUserName) {
if (newUserName) {
if (timeout) {
$timeout.cancel(timeout);
}
timeout = $timeout(function() {
userListService.userList(newUserName)
.success(function(data, status) {
$scope.users = data;
console.log(JSON.stringify(data))
});
}, 350);
}
});
}
]);
Ajax請求本地文件也需要跨域
本地跨域設(shè)置
但是從webstorm直接打開網(wǎng)頁進(jìn)行請求不存在這個問題 這個IDE內(nèi)置服務(wù)器 詳解
Paste_Image.png
Paste_Image.png
Paste_Image.png
搭建項(xiàng)目
步驟
UI-router
angular原生沒法實(shí)現(xiàn)嵌套路由
run()
初始化全局的數(shù)據(jù) , 只對全局作用域起作用 如 $rootScope,局部的$scope不管用,run方法類似于回調(diào)方法,在angular啟動之后執(zhí)行一些動作。
angular run()運(yùn)行塊
AngularJS中run方法的巧妙運(yùn)用