Archive

Posts Tagged ‘angular’

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!

Advertisements

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.

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.