Recently I’ve been trying to create a SharePoint 2013 app using AngularJS and angularui-bootstrap.
It’s been going well thanks to Jeremy Thake’s (@jthake) original demo.
But I wanted more! More than just access to the local site, I wanted access to the web, but I wanted to do it in the right AngularJs way, using the service so later when I figure out how to do DI testing I can, using promises too, which of course SharePoint doesn’t return in a way we can use in AngularJS.
So this code snippet (not complete app) will give you a clue on a way of doing it, there may be a better way to do this in AngularJS Im no expert, I see references to module.Factory calls in other examples, but I’m sticking to Jeremy’s starter code for now.
This example uses UK police data, details of the license are here http://www.nationalarchives.gov.uk/doc/open-government-licence/version/2
'use strict'; var myApp = angular.module("myApp", []); function myAppCtrl($scope, $myDataService) { $scope.getPoliceClick = function () { //Whoops, edited this line as it was wrong from original post var promise = $myDataService.getPolice($scope); promise.then( //Success callback, check the status = 200 and go mad function (response) { //... }, //Epic Fail callback function (response) { //.. } ); }; }; //this method signature is same as Jeremy"s thats why the $http is there, I use it for lists as well //just not in this code sample myApp.service("$myDataService) ", function ($q, $http) { this.getPolice = function ($scope) { var deferred = $q.defer(); var context = SP.ClientContext.get_current(); var request = new SP.WebRequestInfo(); request.set_url("http://data.police.uk/api/bedfordshire/57"); request.set_method("GET"); // We need the response formatted as JSON. request.set_headers({ "Accept": "application/json;odata=verbose" }); var response = SP.WebProxy.invoke(context, request); context.executeQueryAsync( function () { //Notice the scope apply, because the async call is made from outside of angular //just resolving will not work $scope.$apply(deferred.resolve(response)); }, function () { $scope.$apply(deferred.reject(response)); } ); return deferred.promise; }; });
I love seeing how people are using AngularJS with SharePoint 2013. Keep it up!