Showing posts with label angularjs services. Show all posts
Showing posts with label angularjs services. Show all posts

Call a controller from another controller in AngularJS

Whenever you want to share some data between AngularJS controllers or whenever you want to pass some data from one controller to other controller, then you can communicate between controllers in multiple ways.

By Sharing a Service:


You can share a common service between two controllers.

consider you have the following service called 'myService' which returns an array like below.

var myApp = angular.module('myApp', []);
 
myApp.factory('myService'function () {
    return []; //return an array
});

Now you can use this service in your AngularJS controllers like below

function FirstController(myService) {
    //your code here
}
 
function SecondController(myService) {
    //your code here
}

you can also define methods in the service and you can call those methods from controllers.

By Emitting an Event ($emit):


You can dispatch an event using $emit from one controller and you can listen to that event using $on from other controller.

Example:

function FirstController($scope) {
    $scope.$on('someEvent'function (event, args) {
    });
    // this is another controller or even directive
}
 
function SecondController($scope) {
    $scope.$emit('someEvent', args);
}
here orgs means Optional set of arguments which will be passed onto the event listeners.

In this way you can communicate between the controllers in AngularJS.

For more posts on angularJS visit: AngularJS


Read more...

AngularJs Directive for notifications

When ever we are building a webpage we may want to show some notification messages to the users. Here we are going to use JQuery's miniNotiication plugIn to show notifications. You can download this plugin from here: https://github.com/miniJs/miniNotification

download the zip file and add the miniNotification.js file to your project.

Add the following service to your services.js file.

app.factory('NotificationService', ['$rootScope', function ($rootScope) {

    var notificationService = {

        information: function (message) {
          $rootScope.$broadcast("notificationBroadcast", { "Message": message, "Type": 'information' });
        },

        success: function (message) {
          $rootScope.$broadcast("notificationBroadcast", { "Message": message, "Type": 'success' });
        },

        error: function (message) {
          $rootScope.$broadcast("notificationBroadcast", { "Message": message, "Type": 'error' });
        }
    };
    return notificationService;
}]);


we are going to call this service in our controllers whenever we want to show notifications. There are three types of notifications in the service.

1.Notification of type "information"
2.Notification of type "success"
3.Notification of type "error"

And now add the following directive to your directives.js file

app.directive('PostDataNotification', function () {

    return function (scope, element, attrs) {
        scope.$on('notificationBroadcast', function (event, args) {
            scope.notificationMessage = args.Message;
            $('.notification').miniNotification({ time: 3000 });
        });
    };

});


The html code to show the notification

  <div class="notification" post-data-notification="">
            <p>{{notificationMessage}}</p>
   </div>


we are using the "PostDataNotification" directive on the div. Inside the directive we are adding some text to  "notificationMessage".

Now we need to add some styles to notification div. (change the styles as per your requirement)

.notification {
    display: none;
    position: fixed;
    cursor: pointer;
    width: 100%;
    background: #EFEFEF;
    text-align: center;
    z-index: 9999;
    padding: 9px;
    padding-left: 0px;
}

    .notification p {
        font-size: 14pt;
        font-family: 'Segoe UI','Arial';
        margin-top: 5px;
        margin-bottom: 5px;
    }


We are almost done. The last thing is calling the service from our controller.

If you want to show a success notification when a record is saved to database. Then you just call the notificationsService from success function of the ajax/http call.

Example:

        $.ajax({
                type: "POST",
                url: serviceURL,
                data: "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: successFunc,
                error: errorFunc
            });

            function successFunc(data, status) {    
                     NotificationService.success('successfully added data');
            }

            function errorFunc() {
                      NotificationService.error('Error in adding data');
            }
        });


Here we are calling NotificationService which calls Notification directive (using $broadcast and $on).

Hope it helps you.

For more posts on JQuery visit: JQuery

For more posts on AngularJs visit: AngularJS

Read more...