Archive

Archive for the ‘Angular JS’ Category

SharePoint: How to check if page is in edit mode or not in JavaScript

August 28, 2017 Leave a comment

As SharePoint evolved and other client technologies started to become popular and independent we are achieving most of the solution with client side technologies like JavaScript, jQuery and other similar.

I came across one requirement while working on a JavaScript based component, where I need a conditional code to run only when my page is in edit mode. I found multiple solutions which I summaries below.

Option 1:

var inDesignMode = document.forms[MSOWebPartPageFormName].MSOLayout_InDesignMode.value;
if (inDesignMode == "1")
{
// page is in edit mode
}
else
{
// page is in browse mode
}

For Wiki pages

var wikiInEditMode = document.forms[MSOWebPartPageFormName]._wikiPageMode.value;
if (wikiInEditMode == "Edit")
{
// wiki page is in edit mode
}
else
{
// wiki page is not in edit mode
}

Option 2: Using SP.Ribbon.PageState.Handlers.isInEditMode()

ExecuteOrDelayUntilScriptLoaded(function(){
var InEditMode = SP.Ribbon.PageState.Handlers.isInEditMode();
if(InEditMode){
// page is in edit mode
}
}, 'SP.Ribbon.js');

Option 3: While checking the value in SharePoint search display template we need to use Srch.U.isPageInEditMode Method

var isRollupPageInDisplayMode = Srch.ContentBySearch.isRollupPage(ctx.ClientControl) && !Srch.U.isPageInEditMode();

Happy Learning!

Angular JS: date formatting in ng-repeat

Hi Friends,

I was binding some data using angular JS with ng-repeat, in my case there are couple of columns which are dates. From the data source it is coming in different format something like full date as 2017-04-21T09:01:00.000Z

Now I wanted to format it without changing my data source array, one option would be to create a JavaScript Date object and then convert in required format and then update the value in array.

Angular have some easy way to achieve date formatting with ng-repeat.

<div class="dateCreated">{{myobj.CreatedDate | date:'M/d/yy h:mm a'}}</div>

Or we can use fixed formats provided by Angular like ‘short’ or ‘mediumDate’, example

<div class="dateCreated">{{myobj.CreatedDate | date:'short'}}/div>

There are some other formats also available, please refer Angular Date formatting API documentation at https://docs.angularjs.org/api/ng/filter/date

Happy learning!

Angular JS: Calling angular function from jQuery

Hi Friends,

Angular JS and jQuery are best companion and in most of the cases we need to use both of those to achieve some functionality.

I my case as well I was using jQuery UI tabs with Angular JS. Where tabs are manually added but in my case I wanted to call an angular function when tabs are getting changed.

The problem is tabs changed event was non-angular section and $scope was not available in the jQuery tab change event.

Solution:

We need to provide the ID property for controller div where we have defined ng-controller.

<div class="form-group" ng-controller="getTestCtrl" id="ctrlTest">

Then we can call the method from non-angular part of the JavaScript as well, in my case jQuery UI tabs change event.

angular.element('#ctrlTest').scope().GetTestData();

angular.element('#ctrlTest').scope().$apply();

Make sure to call $apply() method which triggers a $digest cycle after calling the function as we are not in Angular cope hence we need  to explicitly call $apply method to force the UI binding.

SharePoint: Access denied error while calling web service from JavaScript

March 6, 2017 3 comments

Hi Friends,

I would like to share one very specific while calling web service from JavaScript, we were getting exception. Important point to note here is the code is working very fine if we access the page on server. But we are getting JavaScript ‘Error: Access is denied.’ Error while accessing the web page from client machine through browser.

error1

We are getting exception where we are calling the web service.

After some analysis the error came out as HTTP and HTTPS mixed content issue.

In our case HTTPS is configured on load balancer level and on ISS 7 level we have HTTP only hence web service call is working fine.

While accessing from outside URL is getting accessed only with HTTPS and non-secured request is also redirected with secured.

Problem fund that we have used ‘_spPageContextInfo.webAbsoluteUrl’ variable which is providing the HTTP path as SharePoint is unaware with existence of HTTPS as it is configured on load balancer level.

‘_spPageContextInfo.webAbsoluteUrl’ is supposed to give HTTPS path if HTTPS configured on ISS 7 level but as in our case SSL is configured on load balancer hence SharePoint is unaware about SSL.

Solution:

We have checked the protocol of the browser request using ‘document.location.protocol’ and if it is HTTPS then we replaced HTTP with HTTPS from the output of ‘_spPageContextInfo.webAbsoluteUrl’

change

This solution is working fine both in the case of HTTPS and HTTP.

Though this scenario is very specific but still this may help someone to understand the issue better.

Angular JS: Calling one controller from another controller

February 20, 2017 Leave a comment

Hi friends,

I came across a requirement where I am having multiple controllers referred on my page and I wanted to call one controller method from another controller.

This is common sacnorao while dealing with multiple controllers.

Problem statement:

Calling one controller method from another controller.

Solution:

We need to use ‘$emit’ and ‘$on’ services for event based communication and expose the function to other controller on $rootScope.

Following code explains how we can achieve this.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.js">
</script>
<script>
var myApp = angular.module('MyTest', []);
myApp.controller('My1Controller', function($scope,$rootScope) {
  $scope.childmethod = function() {
            $rootScope.$emit("CallMy2ControllerMethod", {message: 'in My Controller 2'});
        }
		
		$scope.childmethod2 = function() {
            $rootScope.$emit("CallMy3ControllerMethod", {message: 'in My Controller 3'});
        }
});
myApp.controller('My2Controller', function($scope,$rootScope) {
   $rootScope.$on("CallMy2ControllerMethod", function(event,param1){
           $scope.My2ControllerMethod(param1);
        });

        $scope.My2ControllerMethod = function(param1) {
			alert(param1.message);
        }
});
myApp.controller('My3Controller', function($scope,$rootScope) {
  $rootScope.$on("CallMy3ControllerMethod", function(event,param1){
           $scope.My3ControllerMethod(param1);
        });

        $scope.My3ControllerMethod = function(param1) {
			alert(param1.message);
        }
});
</script>
</head>
<body ng-app="MyTest">
<div ng-controller="My1Controller">
This is "Controller 1"
 <input type="button" value="Call My2Controller" ng-click="childmethod()">

 <input type="button" value="Call My3Controller" ng-click="childmethod2()"></div>
<div ng-controller="My2Controller"></div>
<div ng-controller="My3Controller"></div>
</body>
</html>

In above example we are calling My2Controller and My3Controller methods from My1Controller.

We have made method ‘CallMy2ControllerMethod’ and ‘CallMy3ControllerMethod’ available using ‘$on’ and we can call the method using $emit.

There is another way to use ‘$broadcast’ and ‘$on’ but it’s better to use ‘$emit’ and ‘$on’ as it destroys the listener.

Hope this will help some of the developers.

Angular JS: DataType gets added in value for ng-options when accessing value outside of angular scope

January 12, 2017 Leave a comment

Hi Friends,

While working on Angular JS I came across an issue where value data type got added to option value.

Problem statement:

Check the following ng-options binding.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
 angular.module("BlogTest", []).
 controller("BlogTestController", ["$scope", function($scope) {
 $scope.users = [
 {userId: 101, userName: "One"},
 {userId: 102, userName: "Two"},
 {userId: 103, userName: "Three"}
 ];
 $scope.calculateQuantity = function() {
 var e = document.getElementById("ddlusers");
 var strUser = e.options[e.selectedIndex].value;
 $('#angularselected').html($scope.users1); // output as 101,102,103
 $('#javascriptselected').html(strUser); // output as number:101, number:102, number:103
 $('#jqueryselected').html($("#ddlusers").val()); // output as number:101, number:102, number:103
 };
 }]);
</script>
</head>
<body>
<div ng-app="BlogTest" ng-controller="BlogTestController">
<select ng-model="users1" id="ddlusers" ng-options="user.userId as user.userName for user in users">
</select></br>
Angular selected :: <span id="angularselected"></span></br>
JavaScript selected :: <span id="javascriptselected"></span></br>
jQuery selected :: <span id="jqueryselected"></span></br>
<input type="button" value="Selected value" ng-click="calculateQuantity()"></div>
</body>
</html>

Above code binds the option perfectly but when if we try to access the value outside the angular scope we found that value is getting added with data type of value.

Below screen shot showing the difference between accessing the value within the scope and outside the scope using JavaScript or jQuery.

view1

view2

view3

If you check the rendered HTML you will found as following where datatype gets added in value

view4

Solution:

The solution to this is to use ‘track by’ as shown in below code snippet.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
 angular.module("BlogTest", []).
 controller("BlogTestController", ["$scope", function($scope) {
 $scope.users = [
 {userId: 101, userName: "One"},
 {userId: 102, userName: "Two"},
 {userId: 103, userName: "Three"}
 ];
 $scope.calculateQuantity = function() {
 var e = document.getElementById("ddlusers");
 var strUser = e.options[e.selectedIndex].value;
 $('#angularselected').html($scope.users1); // output as 101,102,103
 $('#javascriptselected').html(strUser); // output as number:101, number:102, number:103
 $('#jqueryselected').html($("#ddlusers").val()); // output as number:101, number:102, number:103
 };
 }]);
</script>
</head>
<body>
<div ng-app="BlogTest" ng-controller="BlogTestController">
<select ng-model="users1" id="ddlusers" ng-options="user.userId as user.userName for user in users track by user.userId">
</select></br>
Angular selected :: <span id="angularselected"></span></br>
JavaScript selected :: <span id="javascriptselected"></span></br>
jQuery selected :: <span id="jqueryselected"></span></br>
<input type="button" value="Selected value" ng-click="calculateQuantity()"></div>
</body>
</html>

Now if you see the result, you will find that datatype got removed from the source HTML

view10

And the result now for Angular and non-angular is same.

view7

view8

view9

Happy coding and Happy New Year 2017.