By kswaughs | Thursday, June 9, 2016

AngularJS Rest Service Example

Use Case
1. Display the list of topics available in www.kswaughs.com
2. Allows user to enter the topic and prints error message if topic is not available
3. Make a rest service call with GET method and print titles of requested topic blog posts

HTML & AngularJS code
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script>
    var app = angular.module('AngularRestApp', []);
    app.controller('restExample', function($scope, $http) {

        $scope.topics = [ 'Java', 'Camel', 'Apache-CXF', 'Junit', 'REST', 'spring' ];

        $scope.submit = function() {

            if ($scope.topics.indexOf($scope.topic) == -1) {
                $scope.error = 'Entered Topic is Not available.' +
                               ' Also, It is a Case sensitive';
            } else {
                $scope.error = '';
                $scope.getBlogPosts();
            }
        };

        $scope.getBlogPosts = function() {

            $http.get(
                    "http://www.kswaughs.com/feeds/posts/summary/-/"
                            + $scope.topic + "?alt=json").then(
                    function(response) {
                        $scope.myData = response.data.feed.entry;
                        $scope.myPost = $scope.topic;
                    });

        };

    });
</script>
</head>
<body>
    <div ng-app="AngularRestApp" ng-controller="restExample">
        <b>List of topics available in www.kswaughs.com</b>
            <ul>
                <li ng-repeat="x in topics">{{$index+1}} {{x}}</li>
            </ul>
            <br/>    
            <label>Topic:</label>
            <input type="text" ng-model="topic" placeholder="Enter topic here"> 
            <input type="button" value="Get Posts" ng-click="submit()" />

        <p ng-bind="error" style="color:red"></p>
        <hr />
        <p>
            <b>Posts of {{myPost}} </b>
        </p>
        <ul>
            <li ng-repeat="entry in myData">
                <a ng-repeat="link in entry.link | filter:{rel: 'alternate'}"
                href="{{link.href}}">{{entry.title.$t}}</a>
            </li>
        </ul>
    </div>
</body>
</html>

DEMO


List of topics available in www.kswaughs.com
  • {{$index+1}} {{x}}

 


Posts of {{myPost}}


Recommend this on