category: AngularJS

AngularJS - $http

on 2014-06-01

AngularJS - $http

Angular use $http handle AJAX behavior. It support method to handle rest API and basic usage. But its default Content-type is application/json

Basic usage

$http({
    method: 'GET', // support GET, POST, PUT, DELETE
    url: '../php/response.php',
    params: data, // GET method query string
    data: data,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    timeout: 30000, // timeout abort AJAX
    cache: false
}).
success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
    console.log(data);
}).
error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
    console.error(data);
});

Refer - $http Refer - AngularJS AJAX

get, post, put, delete, head, jsonp

data is a object like

var data = {user: 'Ted', pwd: 12345};

$http.get(url, config)

$http.post(url, data,config)

$http.put(url, data, config)

$http.delete(url, config)

$http.head(url, config)

$http.jsonp(url, config)

jsonp url must add callback

$http.jsonp(url + '?callback=JSON_CALLBACK').
success(function(data, status, headers, config) {
    console.log(data);
    // this callback will be called asynchronously
    // when the response is available
}).
error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
    console.error(data);
});

PHP handle request

rest API

Beacuse AngularJS default request Content-type is application/json So we must use json_decode

<?php

$request = file_get_contents("php://input");
$method = $_SERVER['REQUEST_METHOD'];
switch($method)
{
    case "PUT":
        print_r($method);
        echo '<br>';
        print_r(json_decode($request, true));
        echo '<br>';
        print_r(json_decode($request, true)['user']);
    break;
    case "GET":
        print_r($method);
        print_r($_GET);
        echo '<br>';
        print_r($_GET['user']);
    break;
    case "DELETE":
        print_r($method);
        echo '<br>';
        print_r(json_decode($request, true));
        echo '<br>';
        print_r(json_decode($request, true)['user']);
    break;
    case "POST":
        print_r($method);
        echo '<br>';
        print_r(json_decode($request, true));
        echo '<br>';
        print_r(json_decode($request, true)['user']);
    break;
}

?>

Other way(only use GET & POST)

Set Content-type as application/x-www-form-urlencoded; charset=UTF-8

  1. Set all request as ‘application/x-www-form-urlencoded; charset=UTF-8’
var module = angular.module('module', []);
module.config(function($httpProvider) {
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});
  1. Set request header if it need
$http({
    method: 'POST',
    url: '../php/response.php',
    data: data,
    headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
}).
success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
    console.log(data);
}).
error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
    console.error(data);
});

And then data is stringify object like

var data = {user: 'Ted', pwd: 12345};
data = 'data=' + JSON.stringify(data);

So php is

<?php

$data = json_decode($_POST['data'], true);
echo $data['user'];
// or
$data = json_decode($_GET['data'], true);
echo $data['user'];

?>

Refer - Angular HTTP post to PHP and undefined

HTTP 標頭參照

Read more

AngularJS - do something after ng-repeat

on 2014-05-25

AngularJS - do something after ng-repeat

在學習用 AngularJS 的過程中遇到個問題就是 ng-repeat 好厲害喔, code 變得好少喔 但我想再 ng-repeat 完移掉 loading view 要怎麼移啊? 用 setTimeout 跟白癡一樣, 又不知道時間要設多久 只好向 fb 求救 沒想到有人立馬給出解決方案 原文來源 blog

由於對 AngularJS 不是了解的很透徹, 所以在此不詳加說明(原文內有說明) 這裡只上 code

HTML


<div id='list' ng-app="testApp">
    <div ng-controller="blogger" >
        <ul>
            <li ng-repeat="list in blog"  on-last-repeat>
                {{list.title.$t}}
            </li>
        </ul>
    </div>
</div>

JavaScript


var module = angular.module('testApp', [])
     .directive('onLastRepeat', function() {
        return function(scope, element, attrs) {
            if (scope.$last) setTimeout(function(){
                scope.$emit('onRepeatLast', element, attrs);
            }, 1);

        };
    })

.controller('blogger', function($scope, $http, $parse) {
        $scope.$on('onRepeatLast', function(scope, element, attrs){
        alert(document.querySelector('#list').offsetHeight + 'px');
      });

         // json callback must JSON_CALLBACK
        $http.jsonp('http://tysh310246.blogspot.com/feeds/posts/default?alt=json&callback=JSON_CALLBACK').success(
            function(data) {
                $scope.blog = data.feed.entry;
            }
        );


});

這段 code 最後 alert 的高度是 ng-repeat 完後 list 的高度

Read more