Thursday, October 2, 2014

SharePoint 2013: List operation using AngularJS Part 2

Below example explains you about how to get List Items using AngularJS service.

HTML Code:
<input ng-model="listName" /> : <input type="button" ng-click="GetListItems()" value="GetListItems" />
<ul>
    <li ng-repeat="listItem in listItems">
        {{listItem.Title}}
    </li>
</ul>
<div>
    {{listItemJSON}}
</div>

Controller File:
var listModule = angular.module('listModule', []);
listModule.controller('listController', ['$scope', 'ListService', function ($scope, ListService) {
    $scope.GetLists = function () {
        ListService.GetLists()
        .success(function (data) {
            $scope.jsonData = JSON.stringify(data);
            var results = data["d"]["results"];
            $scope.lists = results;
        })
        .error(function () {
            alert("error");
        });
    };
    $scope.GetListItems = function () {
        ListService.GetListItems($scope.listName)
        .success(function (data) {
            $scope.listItemJSON = JSON.stringify(data);
            var results = data["d"]["results"];
            $scope.listItems = results;
        })
        .error(function () {
            alert("error");
        });
    };
}]);


Service File:
var listServiceModule = angular.module('listServiceModule', []);
listServiceModule.service('ListService', ['$http', function ($http) {
    var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
    this.GetLists = function () {
        
        var config = {
                headers: {
                    "ACCEPT": "application/json;odata=verbose"
                }
        };
        return $http.get(siteUrl + "/_api/web/lists", config);
    };

    this.GetListItems = function (listName) {
        var config = {
            headers: {
                "Accept": "application/json;odata=verbose"
            }
        };
        return $http.get(siteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items", config);
    };
  
}]);

No comments:

Post a Comment