AngularJS: prevent form validation in Page Edit Mode
By Anatoly Mironov
I work on a cool project where AngularJS is used for rendering of business data in a SharePoint portal. One of the beautiful parts of AngularJS is the client validation. AngularJS understands the new html5 attributes like “required” and pattern, which makes the markup and javascript concise and semantic. Recently I ran into a problem: The SharePoint webparts which had html forms with required fields were impossible to add to a page in the web browser, neither was it possible to edit the pages with these webparts. When I clicked on “Save”, the page tried to validate and failed. The solution for this is very elegant, like much of the AngularJS. If you don’t show your angular form, it won’t validate. So just use any method to detect the edit mode on a SharePoint page. I created a helper function for that. [sourcecode language=“javascript”] function isEditMode() { var publishingEdit = window.g_disableCheckoutInEditMode, form = document.forms[MSOWebPartPageFormName], input = form.MSOLayout_InDesignMode || form._wikiPageMode; return !!(publishingEdit || (input && input.value)); } [/sourcecode] In the angular controller, just define the part of it which shouldn’t be there when you are editing a page, by using ng-hide="editMode"
: [sourcecode language=“html”] [/sourcecode] editMode
is a $scope variable in your controller. So the last thing to do is to get the editMode value by invoking the previously defined isEditMode
function: [sourcecode language=“javascript”] function PhoneCallCtrl($scope, $http) { $scope.editMode = isEditMode(); } [/sourcecode]
Ajax and editMode
Another usage of this approach could be preventing of ajax calls when the page is being edited. There is already an example of this idea (calling ajax only in a view mode) in the standard SharePoint 2013. When you edit a page which has a Microfeed webpart. It won’t get any data until you save the page and switch to the normal page mode.