Skip to main content
Angular Js, SharePoint

AngularJS with SharePoint

In the recent past, web apps have taken on an extremely important role with a prerequisite that they be fast and appealing. More importantly they need to be user friendly. While there are several good technologies to create such apps, I believe that there is one good technology AngularJs, which is extremely useful for creating the structural framework for dynamic web apps. From the client side, AngularJs helps make web apps faster and provides the support required for best user interface. It can be used with any technology including MVC and MVVM frameworks.

Why AngularJs?

We can develop any web application with DOM Manipulation, Data binding etc. However, AngularJS makes this easier. Some key advantages of AngularJs are:

  1. AngularJs supports cross-browser JavaScript code in applications
  2. It is a rich internet application
  3. It is Open Source technology
  4. It has awesome flexibility and makes it easy for developers to code
  5. Increases the business for apps and works with cross technologies.
  6. MVW Framework(Model View What Ever)
  7. Bootstrap

How AngularJS works

Angular Js

Integrating Angular with SharePoint:

SharePoint has the ability to use client-object-model JavaScript and Rest API to create web parts. The advantage of this is, we can use it in .Net, Silver Light etc in JavaScript libraries. Although, SharePoint has server-side code with which we can accomplish a lot of things, there is the off chance that we may not be able to achieve rich user interface and performance – although for this, we could use JQuery or other similar frameworks. When comparing these frameworks, AngularJS is the best way to modify Document-Object-Model (DOM).

Before integrating SharePoint we should know a few things about Angular:

  • Controller – JavaScript functions that are bound to a particular scope.
  • Scope – Objects that refer to the model. They act as a glue between controller and view.
  • Directives – Markers on DOM elements, these can be used to create custom HTML tags that serve as new, custom widgets. AngularJS has built-in directives (ngBind, ngModel, ngBind, etc.)
  • Data-binding – It is the automatic synchronization of data between model and view components.
  • Factory– Factory come with several built-in services for example $http to make an XMLHttpRequests.

Controller:

A Controller is a JavaScript object which contains attributes and functions. A Controller is defined using the AngularJS built-in directive ng-controller. A Controller handles all the operations related to a view to which it has been associated.

A Controller is defined as follows:

angular.module(rootApp, []).controller(home.controller, function($scope) {
});

And the above controller can be declared as follows:

<div id="myDiv" ng-app="rootApp" ng-controller="home.controller">
    ......
</div>

Built-in Directives

As the name itself indicates, Directive is an indicator to the angular compiler. It directs the angular compiler that what to do when it comes across a Directive. AngularJS provides such built-in directives to ease the developer work. Some of the important directives necessary to build an AngularJS app are-

  • ng-app – This directive defines and links an AngularJS application to HTML.
  • ng-controller – This directive associates a controller to a view.
  • ng-model – This directive binds the values of AngularJS application data to HTML input controls.
  • ng-bind – This directive binds the AngularJS Application data to HTML tags.
  • ng-repeat – This directive is used to iterate through a list and generate elements dynamically.

There are many other built-in directives which you can refer from the AngularJS documentation as and how you come across different requirements.

Custom Directives

Custom directives are used to extend the HTML functionality. Custom directives are defined using the “directive” function. A custom directive replaces an element to which it has been applied. Let’s understand this with an example.

I want to define a custom tag as follows, which has an attribute called “title”.

<announcements title=""></announcements >

To handle above custom tag a custom directive has to be written

var app = angular.module(‘rootApp’, []);
app.directive(‘announcements’, function() {
    var directive = {};
    directive.template = "Title: <b>{{ title}}</b> “;
    directive.scope = {
        title: "=title"
    }
    directive.compile = function(element, attributes) {
        element.css("background", "blue");
    }
    return directive;
});

Scope:

It is JavaScript object and it contains the properties and functions although it will interact the controller and view.

$scope.getUser() {
    $scope.User = userInfo;
}

Factory:

This is a simple function. Add some logic and it will return the object. And we can call in controller,service,directive, etc. Create common or helper function in factory to refer in app.

angular.module(rootApp, []).controller(home.factory, function($scope, $http) {
    Var homefactory = {};
    homefactory.getAnnouncements = function() {
        $http.get("url");
    }
    return homefactory;
});

Create sample in SharePoint with Angular.

  1. Download the angular.min.js
  2. The following folder structure need to be create to step Angular with SharePoint.
    a) Map folder site assets module in visual studio.
    b) Inside site assets need to following structure.
    SharePoint
  3. Create home.factory.js inside the factory – Home and add the below code.
    angular.module('home.factories', [])
        .factory('HomeFactory', ['$q', '$http', function($q, $http, ) {
            var homefactory = {};
            var date = new Date();
            var urlHomeSiteCollection = ""; //pass the url here.
    
            homefactory.getAnnouncements = function() {
                    var currentDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
                    var queryUrl = urlHomeSiteCollection + "/_api/web/lists/GetByTitle('Announcements')/items?$Select=Title,Body,Expires,CategoryLookup/Title,CategoryLookup/BackgroundColor,CategoryLookup/TextColor,CategoryLookup/CategoryIcon&$expand=CategoryLookup&$filter=Expires ge datetime'" + currentDate + "T00:00:00'&$orderby=Expires+asc,Modified+desc&$top=10";
                    return $http.get(queryUrl);
                },
                return homefactory;
        }]);
  4. Create home.controller.js inside the controllers- Home and add the below code.
    angular.module('home', [home.controllers ','
                home.factories ']);
                angular.module("home.controllers", ['home.factories']).controller('HomeController', function($scope, HomeFactory) {
                    $scope.Announcements = [];
    
                    function initHome() {
                        loadAnnouncements();
                    }
                    // load announcements and binding
                    function loadAnnouncements() {
                        HomeFactory.getAnnouncements().then(function(result) {
                            if (result.data.d.results && result.data.d.results.length > 0) {
                                bindAnnouncements(result.data.d.results)
                            }
                        }, function(error) {
                            console.log("Error fetching announcements. " + error.data);
                        })
                    };
    
                    function bindAnnouncements(results) {
                        if (results.length > 0) {
                            $.each(results, function(key, value) {
                                var announcement = {
                                    Title: value.Title,
                                    Description: Description
                                };
                                $scope.Announcements.push(announcement);
                            });
                        }
                    };
                    initHome();
                });
  5. Add the below code in rootapp.js. The rootapp.js for inject multiple controllers and make a one app to refer in application.
    var rootApp = angular.module('rootApp', ['home'], function() {});
    angular.module("home", [], function() {});
    angular.module('home').run(function($http) {
        $http.defaults.headers.common["Accept"] = "application/json;odata=verbose";
    });
    Note: if want to refer multiple controllers in page we have to follow as shown as above code.
  6. Add downloaded angular js, jquery inside the lib – Framework folder
  7. Add custom CSS inside the lib – css folder.
  8. Refer angular.js, jquery and rootapp.js sharepoint master page.
  9. Applications that have any CSS, JavaScript function related to the header, footer or any load function should be added to the app.js and refer to the SharePoint master page.
  10. Create the application page and the below scripts and html code.
    <script type="text/javascript" src="/SiteAssets/Content/app/controllers/Home/home.controller.js"></script>
    <script type="text/javascript" src="/SiteAssets/Content/app//factory/Home/home.factory.js"></script>
    <div id="hero-background-image" ng-controller="HomeController">
        <div class="item" ng-repeat="announce in Announcements">
            <div class="carousel-caption">
                <div class="row">
                    <div class="col-sm-4 col-md-2 announcement-category">{{announce.Title}}</div>
                    <div class="col-sm-8 col-md-10 announcement-body">{{announce.Description}}</div>
                </div>
            </div>
        </div>
    </div>
    </div>
    </div>
  11. Deploy the application.

Happy Coding!

Narendra P

Narendra P

Narendra comes with over six years of IT experience. He is currently working with Trigent Software as Senior Software Engineer, focussing on Microsoft technologies, .Net, MVC, Entity Framework, Sql Server and SharePoint 2010/2013. He also has strong experience in JavaScript, Jquery, Handlebar Templates, Backbone Js, AngularJS and TypeScript.

One thought on “AngularJS with SharePoint

Comments are closed.