1

I am working on one very complex functionality in SharePoint 2013 where I need to include angular code as a webpart in pages.

There are several scenarios like,

  1. Masterpage (Shared Layout for header and footer and rest of the stuff) may already contain angularJS file (that can be older version as well).

  2. When we add a web part with angular code in it, I also include angular script reference in it since we never know if master page / shared layout has angular reference or not.

What I tried to reproduce similar situation -

-Included Angular script twice.. First one is older Angular, second is latest one. Code fails to work with following error -

WARNING: Tried to load angular more than once.
Uncaught TypeError: undefined is not a functionangular.js:26130 (anonymous function)

What I want to achieve -

I want to check if master page already has reference to Angular, even if it has, ignore it and prefer the reference I have given because my code will be modular and dependent on the script I want to include (latest one, most probably)

I know this sounds stupid but this is how it works with SharePoint Web parts.. I am sure there will be some way like noConflict in Angular..

Rahul Patil
  • 5,656
  • 6
  • 37
  • 65

1 Answers1

1

To know if angularjs has already been loaded on the page, look for the ng-app attribute on any of the tags.

You may use this function:

function getAllElementsWithAttribute(attribute)
{
  var matchingElements = [];
  var allElements = document.getElementsByTagName('*');
  for (var i = 0, n = allElements.length; i < n; i++)
  {
    if (allElements[i].getAttribute(attribute) !== null)
    {
      // Element exists with attribute. Add to array.
      matchingElements.push(allElements[i]);
    }
  }
  return matchingElements;
}

Then,

getAllElementsWithAttribute('ng-app');

Refer this SO question

Can I get elements by attribute selector when querySelectorAll is not available without using libraries?

It can help you detect the presence of angular. Even I have a similar scenario and would like to know about how to find the angular version and load a recent one.

Community
  • 1
  • 1