kasajian
5/20/2014 - 11:40 PM

Angular Ball Directive.md

HTML:

    <p></p>
    <p>Enter ball type: <input type="text" ng-model="ballType" /></p>
    <ball ng-init="ballType='red'"type="{{ballType}}" />

JavaScript:

angular.module('app').directive('ball', ['googleFactory', function (googleFactory) {

    var setAttribute = function(attrs, newValue, element) {

        googleFactory.getSearchResults("+ball " + newValue, 'images').then(function (response) {
            var currentValue = element[0].attributes['type'].value;
            if (currentValue !== newValue) {
                setAttribute(attrs, currentValue, element);
            } else {
                var results = response.data.responseData.results;
                attrs.$set('src', results[0].unescapedUrl);
            }
        }).catch(function (error) {
            console.error(error);
        });
    };

    return {
        restrict: 'E',
        template: '<img height="100"/>',
        replace: true,
        link: function (scope, element, attrs) {
            attrs.$observe('type', function(newValue, oldValue) {
                if (newValue !== oldValue) {
                    setAttribute(attrs, newValue, element);
                }
            });
        },
    };
}]);


angular.module('app').factory('googleFactory', ['$http', function ($http) {

    // what = 'web', 'images', 'local', 'video', blogs', 'news', 'books', 'patent', etc.
    var getSearchResults = function (searchTerm, what) {

        if (httpPromise) {
            console.log("Rejected: " + searchTerm);
            return httpPromise;
        }

        console.log("Searching: " + searchTerm);

        var host = 'https://ajax.googleapis.com/ajax/services/search/' + what;
            
        var args = {
            'version': '1.0',
            'searchTerm': searchTerm,
            'results': '1',
            'callback': 'JSON_CALLBACK'
        };
        var params = ('?v=' + args.version + '&q=' + args.searchTerm + '&rsz=' +
            args.results + '&callback=' + args.callback);

        httpPromise = $http.jsonp(host + params);

        return httpPromise.then(function (response) {
            return response;
        }).catch(function(error) {
            console.error(error);
        }).finally(function() {
            httpPromise = null;
        });
    };

    var httpPromise = null;

    return {
        getSearchResults: getSearchResults
    };
}]);