Search This Blog

Friday, May 27, 2016

Pagination with AngularJS and your API

// main.js (function() { 'use strict'; angular.module('app') .controller('MainCtrl', ['$scope', '$http', function($scope, $http) { $scope.main = { page: 1, take: 15 }; $scope.loadPage = function() { // You could use Restangular here with a route resource. $http.get('api/v2/users?page=' + main.page + '&take=' + main.take).success(function(data){ // users from your api $scope.main.users = data.users; // number of pages of users $socpe.main.pages = data.pages; }); }; $scope.nextPage = function() { if ($scope.main.page < $scope.main.pages) { $scope.main.page++; $scope.loadPage(); } }; $scope.previousPage = function() { if ($scope.main.page > 1) { $scope.main.page--; $scope.loadPage(); } }; }]); }); // main.tpl.html <ul> <li ng-repeat='user in users'>{{ user.email }}</li> </ul> <button ng-click='previousPage()'>Previous<button> <button ng-click='nextPage()'>Next<button>

Get All Of Specific Column in TD and TR Using Rest Api

</style>
<script type="text/javascript">

$(document).ready(function(){
   GetListItems();
});
function GetListItems()  
    var strHtml ="";
    var Increment=0;
    var tbl=$("#GetItems");
    var url = _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('NGOPortals')/items"; 
    $.ajax 
    ({ 
        url: url, 
        type: "GET", 
        headers: 
        { 
            "Accept": "application/json;odata=verbose", 
            "Content-Type": "application/json;odata=verbose",
           
        }, 
        success: function(data)  
        { 
                strHtml +='<tr>';
            $.each(data.d.results, function(key, item) 
            {
                                if(Increment%6 == 0)
                                {
                                                                                strHtml +='<td>';
                                                                                                               
                                }
                                 strHtml +="<div><a href="+item.URL.Url.toString()+" target=\"_blank\">"+item.URL.Description.toString()+"</a></div>";
                                 Increment =Increment +1;
                                 
                if(Increment%6 == 0)
                                {
                                                                                strHtml +='</td>';                           
                                }

             
             
             
            });
             strHtml +='</tr>';
            $("#GetItems>tbody").html(strHtml);
             //var rowCount = $('#GetItems tr').length;
            // alert(rowCount); 
            $("#GetItems").show();
            
       
        }, 
        error: function(data)  
        { 
            //alert("Failed to get list items."); 
        } 
    }); 
  
}
</script>

Saturday, May 21, 2016

Angular Js 1.0 With Rest API In SharePoint 2013 and Angular JS 2.0


Include HTML in Single Page Application

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="IncudeHTMl.aspx.cs" Inherits="AjaxApp.Angular_Js.IncudeHTMl" %>

<!DOCTYPE html>

<html>
   <head>
      <title>Angular JS Includes</title>
   
       <script src="../Script/angular.min.js"></script>
      <style>
         table, th , td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
         }
       
         table tr:nth-child(odd) {
            background-color: #f2f2f2;
         }
       
         table tr:nth-child(even) {
            background-color: #ffffff;
         }
      </style>
     
   </head>
   <body>
     
      <h2>AngularJS Sample Application</h2>
     
      <div ng-app = "mainApp" ng-controller="studentController">
         
          <Div style="background-color:azure">
         <div ng-include = "'/Angular%20Js/main.html'"></div>
         <div ng-include = "'/Angular%20Js/Students.html'"></div>

          </Div>
       
          <br />
          <br />
<div style="background-color:aqua">
 <div ng-controller="studentController1" >
         
         <div ng-include = "'/Angular%20Js/main1.html'"></div>
         <div ng-include = "'/Angular%20Js/Students1.html'"></div>
      </div>

</div>
       
     <div style="background-color:gray">
  <div ng-controller = "shapeController">
            <p>{{message}} <br/> {{type}} </p>
         </div>
         
          <div ng-controller = "circleController">
            <p>{{message}} <br/> {{type}} </p>
         </div>
       
         <div ng-controller = "squareController">
            <p>{{message}} <br/> {{type}} </p>
         </div>

     </div>    
         
 </div>
     
      <script>
          var mainApp = angular.module("mainApp", []);
          mainApp.controller('studentController', function ($scope) {
              $scope.student = {
                  firstName: "Mahesh",
                  lastName: "Parashar",
                  fees: 500,

                  subjects: [
                     { name: 'Physics', marks: 70 },
                     { name: 'Chemistry', marks: 80 },
                     { name: 'Math', marks: 65 },
                     { name: 'English', marks: 75 },
                     { name: 'Hindi', marks: 67 }
                  ],

                  fullName: function () {
                      var studentObject;
                      studentObject = $scope.student;
                      return studentObject.firstName + " " + studentObject.lastName;
                  }
              };
          });
         //var mainApp1 = angular.module("mainApp1", []);
          mainApp.controller('studentController1', function ($scope) {
              $scope.Ram = {
                  firstName: "Ram",
                  lastName: "Vinay",
                  fees: 6666,

                  subjectsRam: [
                     { name: 'Physics', marks: 70 },
                     { name: 'Chemistry', marks: 80 },
                     { name: 'Math', marks: 65 },
                     { name: 'English', marks: 75 },
                     { name: 'Hindi', marks: 67 }
                  ],

                  fullName: function () {
                      var studentObject;
                      studentObject = $scope.Ram;
                      return studentObject.firstName + " " + studentObject.lastName;
                  }
              };
          });

          mainApp.controller("shapeController", function ($scope) {
              $scope.message = "In shape controller";
              $scope.type = "Shape";
          });

          mainApp.controller("circleController", function ($scope) {
              $scope.message = "In circle controller";
          });

          mainApp.controller("squareController", function ($scope) {
              $scope.message = "In square controller";
              $scope.type = "Square";
          });
      </script>
     
   </body>
</html>


Angular JS Click header link to sort, input into filter text to filter























<html>
 <head>
   <title> Angular JS table sort and filter example </title>
 
   
     <script src="../Script/angular.min.js"></script>

   <script>
       var app = angular.module('MyForm', []);
       app.controller('myCtrl', function ($scope) {
           $scope.predicate = 'name';
           $scope.reverse = true;
           $scope.order = function (predicate) {
               $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
               $scope.predicate = predicate;
           };
       });
   </script>
   <style>
     .odd {
       background-color: antiquewhite;
       color: #008b8b;
     }
     td th {
       height: 30px;
       min-width: 100px;
     }
     thead {
       background-color: darkcyan;
       color: white;
       height: 30px;
     }
   </style>
 </head>
 <body ng-app="MyForm" ng-controller="myCtrl">
   <h3>List students</h3>
   <div ng-init=" students = [
            {name: 'Kevin', age: 25, gender: 'boy'},
            {name: 'John', age: 30, gender: 'girl'},
            {name: 'Laura', age: 28, gender: 'girl'},
            {name: 'Joy', age: 15, gender: 'girl'},
            {name: 'Mary', age: 28, gender: 'girl'},
            {name: 'Peter', age: 95, gender: 'boy'},
            {name: 'Bob', age: 50, gender: 'boy'},
            {name: 'Erika', age: 27, gender: 'girl'},
            {name: 'Patrick', age: 40, gender: 'boy'},
            {name: 'Tery', age: 60, gender: 'girl'}
           ] ">
     <pre>Click header link to sort, input into filter text to filter</pre>
     <hr />
     <table class="table table-striped">
       <thead>
         <tr>
         
           <th>
             <a href="" ng-click="order('name')">Name</a>
           </th>
           <th><a href="" ng-click="order('age')"> Age</a> </th>
           <th><a href="" ng-click="order('gender')">Gender</a> </th>
         </tr>
       </thead>
       <tbody>
         <tr>
         
           <td> <input type="text" ng-model="search.name" /></td>
           <td> <input type="text" ng-model="search.age" /> </td>
           <td><input type="text" ng-model="search.gender" /> </td>
         </tr>
         <tr ng-repeat="user in students | orderBy:predicate:reverse | filter:search" ng-class-odd="'odd'">
         
           <td>{{ user.name}}</td>
           <td>{{ user.age}}</td>
           <td>{{ user.gender}}</td>
         </tr>
       </tbody>
     </table>
   </div>
 </body>
 </html>

Validation With Angular JS

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Aj.aspx.cs" Inherits="AjaxApp.Angular_Js.Aj" %>

<!DOCTYPE html>

<html>
   <head>
      <title>Angular JS Forms</title>
       <script src="../Script/angular.min.js"></script>
     
      <style>
         table, th , td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
         }
       
         table tr:nth-child(odd) {
            background-color: #f2f2f2;
         }
       
         table tr:nth-child(even) {
            background-color: #ffffff;
         }
      </style>
     
   </head>
   <body>
     
      <h2>AngularJS Sample Application</h2>
      <div ng-app = "mainApp" ng-controller = "studentController">
       
         <form name = "studentForm" novalidate>
            <table border = "0">
               <tr>
                  <td>Enter first name:</td>
                  <td><input name = "firstname" type = "text" ng-model = "firstName" required>
                     <span style = "color:red" ng-show = "studentForm.firstname.$dirty && studentForm.firstname.$invalid">
                        <span ng-show = "studentForm.firstname.$error.required">First Name is required.</span>
                     </span>
                  </td>
               </tr>
             
               <tr>
                  <td>Enter last name: </td>
                  <td><input name = "lastname"  type = "text" ng-model = "lastName" required>
                     <span style = "color:red" ng-show = "studentForm.lastname.$dirty && studentForm.lastname.$invalid">
                        <span ng-show = "studentForm.lastname.$error.required">Last Name is required.</span>
                     </span>
                  </td>
               </tr>
             
               <tr>
                  <td>Email: </td><td><input name = "email" type = "email" ng-model = "email" length = "100" required>
                     <span style = "color:red" ng-show = "studentForm.email.$dirty && studentForm.email.$invalid">
                        <span ng-show = "studentForm.email.$error.required">Email is required.</span>
                        <span ng-show = "studentForm.email.$error.email">Invalid email address.</span>
                     </span>
                  </td>
               </tr>
             
               <tr>
                  <td>
                     <button ng-click = "reset()">Reset</button>
                  </td>
                  <td>
                     <button ng-disabled = "studentForm.firstname.$dirty &&
                        studentForm.firstname.$invalid || studentForm.lastname.$dirty &&
                        studentForm.lastname.$invalid || studentForm.email.$dirty &&
                        studentForm.email.$invalid" ng-click="submit()">Submit</button>
                  </td>
               </tr>

            </table>
         </form>
      </div>
     
      <script>
          var mainApp = angular.module("mainApp", []);
          mainApp.controller('studentController', function ($scope) {
              $scope.reset = function () {
                  $scope.firstName = "Mahesh";
                  $scope.lastName = "Parashar";
                  $scope.email = "MaheshParashartutorialspoint.com";
              }
              $scope.reset();
          });
      </script>
   </body>
</html>

Monday, May 16, 2016

How to Insert, Update Delete List items using REST API in SharePoint2013 ?

In this post we are going learn how to do CRUD(Create, Read, Update and Delete) operations using SharePoint2013 REST API .


Before learning how to write the script, you should know where to write the script?

This depends on your requirement, lets suppose if you are implementing a visual web part then you can write the script on your user control( .ascx file) in script tag as shown below. You can write your script in a function and then call that function wherever you want. 

In the below script I am calling the script on document ready function

<script type="text\javascript">

$(document).ready( function(){

             // Calling function  
             GetListItembyID();

});

function GetListItembyID(){

            //write your script to get the list item based on id here

}

</script>

Or else you can write the script in a Content Editor web part like as mentioned above.


Reading list item based on item id

Here is the following scenario, I just want to fetch some data based on item id from a list.

In this case we need to use GET http method to fetch/read items. Following are the sample snippets which I used to fetch some of the columns(Title, Name, Email ) information of the item having ID as 1 from the list titled EMPMaster.


$.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/getitembyid('1')/?$select=Title, Name, Email",
              type: "GET",
              headers: {
                               "accept":  "application/json; odata=verbose"
                            },
              success: function(data){
                                alert(data.d.Title); //You will get title here 
                                alert(data.d.Name); //You will get name here 
                                alert(data.d.Email); //You will get email here 
                            },
              error: function(err){
                                alert("Error while fetching list item: " + JSON.stringify(err));
                            }

          });


Reading multiple list items

In the below snippet I used to fetch columns(Title, Name, Email ) information of all items from the list titled EMPMaster.

$.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items?$select=Title, Name, Email",
              type: "GET",
              headers: {
                               "accept":  "application/json; odata=verbose"
                            },
              success: function(data){
                               // Looping multiple items
                               $.each(data.d.results, function(index, item){
                                     alert(Item: " + index);
                                     alert(item.Title); //You will get title here 
                                     alert(item.Name); //You will get name here 
                                     alert(item.Email); //You will get email here 
                                 });
                            },
              error: function(err){
                                alert("Error while fetching list items: " + JSON.stringify(err));
                            }

          });



Inserting list item

In the below snippet I have added list item having columns(Title, Name, Email ) values as "ABC", "XYZ",xyz@abc.com in to the list titled EMPMaster.

$.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items",
              type: "POST",
              data: JSON.stringify({
                                                   '__metadata': {'type': 'SP.Data.EMPMasterListItem' },
                                                   'Title': 'ABC',
                                                   'Name': 'XYZ',
                                                   'Email': 'xyz@abc.com'
                                                }),
              headers: {
                               "Accept": "application/json;odata=verbose",
                               "content-type": "application/json; odata=verbose",
                               "X-RequestDigest": $("#__REQUESTDIGEST").val()
                            },
              success: function(data){
                              alert("Item added successfully!");
                            },
              error: function(err){
                                alert("Error while adding item: " + JSON.stringify(err));
                            }

          });



Updating list item based on item id

In the below snippet I have updated list item column "Name" value to "XYZ1" having id as 1  in the list titled EMPMaster.

$.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items(1)",
              type: "POST",
              data: JSON.stringify({
                                                   '__metadata': {'type': 'SP.Data.EMPMasterListItem' },
                                                   'Name': 'XYZ1'
                                                }),
              headers: {
                               "Accept": "application/json;odata=verbose",
                               "content-type": "application/json; odata=verbose",
                               "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                               "X-HTTP-Method": "MERGE",
                               "If-Match": "*"
                            },
              success: function(data){
                              alert("Item updated successfully!");
                            },
              error: function(err){
                                alert("Error while updating item: " + JSON.stringify(err));
                            }

          });



Deleting list item based on item id

In the below snippet I have deleted list item having id as 1 in the list titled EMPMaster.

$.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items(1)",
              type: "POST",
              headers: {
                               "Accept": "application/json;odata=verbose",
                               "content-type": "application/json; odata=verbose",
                               "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                               "X-HTTP-Method": "DELETE",
                               "If-Match": "*"
                            },
              success: function(data){
                              alert("Item deleted successfully!");
                            },
              error: function(err){
                                alert("Error while deleting item: " + JSON.stringify(err));
                            }

          });


So thats it for now. Hope you learn some basic operations using REST apis in SharePoint 2013.