Ads

Friday, 17 February 2017

AngularJS in a SharePoint 2013 page to add list item using CSOM

Before proceed, I recommend you to go through Learn Angular js for better understanding.

Lets create one simple list form in angular to submit list item.

  1. Create one custom list "Employee Details"
    • FirstName, LastName, Location 
  2. Add one script editor web part to add script in page
    • Add web part --> Media & Content --> Script Editor --> ok to Add it
  3. Edit webpart in "edit Snippet" and write below codes

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>  
<script>  
    function ContactsCtrl($scope) {  
        $scope.contact = { firstName: "", lastName: "", location: "" };  
        $scope.addContact = function ($event) {  
            var x = $scope.contact;  
            $event.preventDefault();  
            var clientContext = new SP.ClientContext.get_current();  
            var web = clientContext.get_web();  
            var list = web.get_lists().getByTitle('Employee Details');  
  
            // create the ListItemInformational object  
            var listItemInfo = new SP.ListItemCreationInformation();  
            // add the item to the list  
            var listItem = list.addItem(listItemInfo);  
            // Assign Values for fields  
            listItem.set_item('Title', x.firstName);  
            listItem.set_item('LastName', x.lastName);  
            listItem.set_item('FullName', x.firstName + " " + x.lastName);  
            listItem.set_item('Location', x.location);  
  
            listItem.update();  
  
            clientContext.executeQueryAsync(  
                Function.createDelegate(this, onQuerySucceeded),  
                Function.createDelegate(this, onQueryFailed)  
            );  
  
        };  
  
        onQuerySucceeded = function () {  
            alert('Successfully updated the contact');  
        }  
  
        onQueryFailed = function (sender, args) {  
            alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
        }  
    }  
</script>  
   
<h1>Employee Information:</h1>  
<br />  
<div ng-app="">  
    <div ng-controller="ContactsCtrl">  
        <strong>Emp First Name</strong>  
        <input type="text" ng-model="contact.firstName" /><br />  
        <br />  
        <strong>Emp Last Name</strong>   
        <input type="text" ng-model="contact.lastName" /><br />  
        <br />  
        <strong>Emp Location </strong> 
        <input type="text" ng-model="contact.location" /><br />  
        <br />  
        <input type="submit" value="Submit" ng-click="addContact($event)" />  
    </div>  
</div>  


No comments:

Post a Comment

Ads