SharePoint 2010, REST, AngularJS

SharePoint 2010 has a REST API that will allow you to easily make calls from JavaScript to things like lists. The following function handles getting items from a list and converting them to an array of JavaScript objects.

function getListItems(listName, cb){
  var baseUrl = '//path/to/site/';
  var serviceUrl = baseUrl + '_vti_bin/listdata.svc/';
  var xhr = new XMLHttpRequest();
  xhr.open('GET', serviceUrl + listName);
  xhr.setRequestHeader('accept', 'application/json');
  xhr.onreadystatechange = function(){
    if(this.readyState === 4){
      var responseObj = JSON.parse(this.responseText);
      var results = responseObj.d.results;
      cb(results);
    }
  }
  xhr.send();
}

Even reading these list items has applications for SharePoint forms and rendering custom UIs. For example:

// filter dropdown
getListItems('Choices', function(choices){
  var selectEl = document.getElementById('#some-select-field');
  for(var i = 0; i < choices.length; i++){
    var optionEl = document.createElement('option');
    optionEl.value = choice.Value;
    selectEl.appendChild(optionEl);
  }
});

Or… if you're using AngularJS (which is great, BTW), you may do something like this.

<ul>
  <li ng-repeat="item in items">
    {{item.Title}}
  </li>
</ul>
var app = angular.module("spApp", []);
app.controller("ctrl", function($scope) {
  $scope.items = [];
  $scope.initItems = function(items){
    this.items = items;
  }
  getListItems('Tasks', $scope.initItems);
});

It's also possible to use POST to make changes to list items, but the type of list items you use may make it difficult to implement. Note that you will likely want to use a "JSON polyfill" as SharePoint 2010 may include a meta tag that makes Internet Explorer forget JSON.

You may also like

  • AngularJS 와 VueJS 반응성

    VueJS는 우리가 가지고 있는 자바스크립트 프레임워크의 생태계에서 비교적 새로운 라이브러리다. 여윈반면 JS는 오랫동안 자리를 잡았고 많은 후원을 받고 있다. 그러나 한 개발자의 MV* 라이브러리는 흥미로운 대안일 수 있다.

    Read More >
  • Angular vs. Vue.js Reactivity

    VueJS is a relatively new library in this ecosystem of JavaScript frameworks that we have. AngularJS has, on the other hand, been long established and has a lot of backing. However, one developer's MV* library may prove to be an interesting alternative.

    Read More >