Sunday, December 27, 2015

Bind data from XML using Angularjs

Angularjs - XML Bind data - bind first element from xml file.


Hello It's easy to bind data from JSON in html using Angularjs. but now a days people are not using XML  file for communicate between client and server.

We have one API service which will return XML object.


Above API return word of the day 

HTML Will like below 


<html>
   <head id="Head1" runat="server">
      <title></title>
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
      <script type="text/javascript">
         var myApp = angular.module('myApp', []);
         
         myApp.controller('myController', function ($scope, $http) {
         
         
         
             $http.get("http://api.wordnik.com/v4/words.xml/wordOfTheDay?api_key=a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5").success(function (xml) {
         
                 $scope.word = $(xml).find('word').text();
                 $scope.defination = $(xml).find('definition text').text();
                 $scope.example = $(xml).find('example text:first').text();
                 $scope.date = $(xml).find('publishDate').text();
         
             }).error(function (status) {
                 alert(status);
         
             });
         
     
         
         
         
         
         
         });
         
         
      </script>
   </head>
   <body>
      <div ng-app="myApp" ng-controller="myController">
         Word : <b>{{word}} </b><b>{{date | date:'MM/dd/yyyy'}}</b>
         <br />
         Defination <b>{{defination}}</b>
         <br />
         Example : <b>{{example}}</b>
         <br />
         Example : <b>{{example2}}</b>
         <h3></h3>
       
      </div>
   </body>
</html>

Sunday, December 13, 2015

Infinite scroll Using Angularjs || facebook style data load on scroll

Load data from web Api and bind using AngularJS with infinite scroll.

Step 1 : Create WebApi for Fetch data.

         Web API will give output like below JSON format.  We want to load data on scroll of a browser.

         so in below json list highlighted in yellow color background will added in listview.


Httpget request Response in JSON

{
   "GetTimeZoneResult": {
    "IsSuccess": true,
    "lstTimezone": [

         {

            "Text": "International Date Line",
            "Value": "-720"

         },

         {

            "Text": "Midway",
            "Value": "-660"

         },

         {

            "Text": "Hawaii",
            "Value": "-600"

         },

      
         {

            "Text": "Abu Dhabi",

            "Value": "240"

         }

      ]

   }

}


2 Import Iconic bundle JS.


  <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
  <script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>


3. Create Angular app, Model &  factory.

 angular.module('ionicApp', ['ionic'])

.factory('PersonService', function ($http) {
    var BASE_URL = "http://localhost/msr/Common.svc/GetTimeZone";
    // var BASE_URL = "http://api.randomuser.me/";
    var items = [];

    return {
        GetFeed: function () {
            return $http.get(BASE_URL).then(function (response) {
                items = response.data.GetTimeZoneResult.lstTimezone;
                return items;
            });
        },
        GetNewUsers: function () {
            return $http.get(BASE_URL).then(function (response) {
                items = response.data.GetTimeZoneResult.lstTimezone;
                return items;
            });
        }
    }
})

.controller('MyCtrl', function ($scope, $timeout, PersonService) {
    $scope.items = [];

    PersonService.GetFeed().then(function (items) {
        $scope.items = items;
    });

    $scope.loadMore = function () {
        PersonService.GetNewUsers().then(function (items) {


            $scope.items = $scope.items.concat(items);

            $scope.$broadcast('scroll.infiniteScrollComplete');
        });
    };

});



so we have created angular app & model and factory for load data on scroll.

Final HTML Page look like below 


<html ng-app="ionicApp">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">

    <title>Ionic Pull to Refresh</title>

    <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
    <script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
    <style type="text/css">
        body {
            cursor: url('http://ionicframework.com/img/finger.png'), auto;
        }
    </style>
    <script type="text/javascript">
        angular.module('ionicApp', ['ionic'])

.factory('PersonService', function ($http) {
    var BASE_URL = "http://localhost/msr/Common.svc/GetTimeZone";
    // var BASE_URL = "http://api.randomuser.me/";
    var items = [];

    return {
        GetFeed: function () {
            return $http.get(BASE_URL).then(function (response) {
                items = response.data.GetTimeZoneResult.lstTimezone;
                return items;
            });
        },
        GetNewUsers: function () {
            return $http.get(BASE_URL).then(function (response) {
                items = response.data.GetTimeZoneResult.lstTimezone;
                return items;
            });
        }
    }
})

.controller('MyCtrl', function ($scope, $timeout, PersonService) {
    $scope.items = [];

    PersonService.GetFeed().then(function (items) {
        $scope.items = items;
    });

    $scope.loadMore = function () {
        PersonService.GetNewUsers().then(function (items) {


            $scope.items = $scope.items.concat(items);

            $scope.$broadcast('scroll.infiniteScrollComplete');
        });
    };

});

    </script>

</head>
<body ng-controller="MyCtrl">

    <ion-header-bar class="bar-positive">
        <h1 class="title">Infinite Scroll</h1>
    </ion-header-bar>

    <ion-content>
        <ion-list>
            <ion-item class="item-avatar" ng-repeat="item in items">
                {{$index}}:    {{ item.Text}}  {{item.Value}}

        </ion-list>

        <ion-infinite-scroll on-infinite="loadMore()" distance="5%"></ion-infinite-scroll>

    </ion-content>


</body>
</html>


you have to bind your list array from your webapi to angular scope variable. 









Friday, December 11, 2015

Agnularjs infinite scrolling- add object to ng-repeat


Angularjs example for load on demand / lazy loading ,facebook like pagination with angularjs.

article from : http://plnkr.co/edit/9WpuUJ?p=info

1. Html

<!DOCTYPE html>
<html ng-app="appModule">
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.css">
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="//code.angularjs.org/1.3.0/angular.js"></script>
    <script src="Scripts/Controllers/app.js"></script>
    <script src="Scripts/Controllers/Scroll.js"></script>

    <style>
        /* Styles go here */

        .glyphicon-refresh-animate {
            -animation: spin .7s infinite linear;
            -webkit-animation: spin2 .7s infinite linear;
        }

        @-webkit-keyframes spin2 {
            from {
                -webkit-transform: rotate(0deg);
            }

            to {
                -webkit-transform: rotate(360deg);
            }
        }

        @keyframes spin {
            from {
                transform: scale(1) rotate(0deg);
            }

            to {
                transform: scale(1) rotate(360deg);
            }
        }
    </style>

</head>
<body ng-controller="appController">
    <div style="margin: auto;width:50%">
        <list-infinitescroll datasource="datasource"
                             list-title="{{'Infinite Scroll Demo'}}"
                             do-load-more="doLoadMore">
            <div>
                <img ng-src="http://placehold.it/{{divWidth}}x100&text={{item.name + item.id}}">
            </div>
        </list-infinitescroll>
    </div>
</body>
</html>




2.scroll.js



(function () {
    angular.module('infinitescrollModule', [])
        .directive('listInfinitescroll', function () {
            return {
                restrict: 'E',
                scope: {
                    listTitle: '@',
                    datasource: '=',
                    doLoadMore: '=',
                },
                transclude: 'true',
                templateUrl: 'Listview.html',
                link: function (scope, element, attrs) {
                    scope.divWidth = document.getElementById('myDiv').offsetWidth - 60
                    scope.loadMore = function () {
                        if (scope.doLoadMore) scope.doLoadMore()
                    }
                }

            }
        })
        .directive('inject', function () {
            return {
                restrict: 'A',
                link: function (scope, element, attrs, ctrl, transcludeFn) {
                    if (!transcludeFn) return;
                    transcludeFn(scope, function (clone) {
                        element.empty();
                        element.append(clone);
                    });
                }
            }
        })
        .directive('whenScrollBottom', function () {
            return function (scope, elem, attr) {
                var scrollBar = elem[0]
                elem.bind('scroll', function () {
                    if (scrollBar.scrollTop + scrollBar.offsetHeight >= scrollBar.scrollHeight) {
                        scope.$apply(attr.whenScrollBottom);
                    }
                })
            }
        })
})()



3.app.js


(function () {
    angular.module('appModule', ['infinitescrollModule'])
        .controller('appController', function ($scope) {
            $scope.oneceToShow = 20
            $scope.datasource = []
            $scope.init = function () {
                $scope.sourcePush(0, $scope.oneceToShow)
            }
            $scope.doLoadMore = function () {
                var start = $scope.datasource.length
                var end = start + $scope.oneceToShow
                $scope.sourcePush(start, end)
            }
            $scope.sourcePush = function (start, end) {
                for (var i = start; i < end; i++) {
                    $scope.datasource.push({
                        name: 'a',
                        id: i
                    })
                }
            }
            $scope.init()
        })

})()


4. Listview.html (repeated html content)


<div class="panel panel-success">
    <div class="panel-heading"><h3>{{listTitle}}</h3> <div class="list-group-item" align="center" ng-show="isBusy"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span>Loading...</div></div>
    <div id="myDiv" style="overflow: auto;max-height: 600px" when-scroll-bottom="loadMore()">
        <li class="list-group-item" ng-repeat="item in datasource">
            <div ng-transclude inject></div>
        </li>
    </div>
</div>





Sunday, December 6, 2015

AnglularJS WIth Webservice IN MVC


$http Post Method With And Withour parameter



<!doctype html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.17/angular.min.js"></script>
 
    <script>
        var mainApp = angular.module("mainApp", []);
        mainApp.controller('tripController', function ($scope, $http) {
            var parameter = JSON.stringify('{ClientId:130}');
            $http({
                method: 'POST',
                data: { ClientId: "130" },
                url: 'http://localhost/msr/ContactService.svc/GetContact'
            })
       .success(function (data) {
           $scope.contacts = data;
       });
        });


        mainApp.controller('TimeZoneController', function ($scope, $http) {
            alert("In");
            $http({
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                url: 'http://localhost/msr/Common.svc/GetTimeZone'
            })
        .success(function (data) {
            $scope.timezones = data;
        });
        });
    </script>

</head>

<body>
    <h2>AngularJS Sample Application</h2>
    <div ng-app="mainApp">
        <div ng-controller="tripController">
            <table>
                <tr>
                    <td>ClientId</td>
                    <td>ContactId</td>
                    <td>Names</td>
                    <td>Email</td>
                </tr>
                <tr ng-repeat="contact in contacts.lstContact">
                    <td>{{ contact.ClientId }}</td>
                    <td>{{ contact.ContactId }}</td>
                    <td>{{ contact.Name}}</td>
                    <td>{{ contact.EmailOrMobile }}</td>

                </tr>
            </table>
        </div>


        <h2>Time Zone</h2>
        <div ng-controller="TimeZoneController">
            <table>
                <tr>
                    <td>Text</td>
                    <td>Value</td>
                </tr>
                <tr ng-repeat="timezone in timezones.GetTimeZoneResult.lstTimezone">
                    <td> {{ timezone.Text }} </td>
                    <td> {{ timezone.Value }} </td>
                </tr>

            </table>

        </div>
    </div>

</body>

</html>




Featured Post