Showing posts with label angular directives. Show all posts
Showing posts with label angular directives. 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...

Dynamically apply a class using AngularJS

Angular provides ng-class directive for adding/removing css styles dynamiucally.

According to angular docs: The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.

ng-class accepts an "expression" that must evaluate to one of the following:

1.a string of space-delimited class names
2.an array of class names
3.a map/object of class names to boolean values

Lets say you are showing a list of items using ng-repeat and each item has a corresponding checkbox. Now when a checkbox is checked then you want to apply some styles to that respective item (like changing the color etc). This can de done using ng-class. Look at the below code to see how it works.

Example:

html code:

<div ng-controller="MyCtrl">
    <div ng-repeat="item in items" ng-class="{'selected-item': item.checked}">
        <input type="checkbox" ng-model="item.checked">
        {{item.name}}{{item.title}}
    </div>
</div>

javascript:

var myApp = angular.module('myApp', []);
 
function MyCtrl($scope) {
    $scope.items = [
        {
            name: 'Misko',
            title: 'Angular creator'
        },
        {
            name: 'Igor',
            title: 'Meetup master'
        },
        {
            name: 'Vojta',
            title: 'All-around superhero'
        }
 
    ];
}

css:

.selected-item {
    colorgreen;
}


When you click on a checkbox, the class "selected-item" gets added to the particular item and the color will be changed to green as mentioned in css.

For live example look at this fiddler: http://jsfiddle.net/codingsolver/dxBdR/

Note: If a class was already applied then the directive will not add duplicate class. When expression changes , newly added classes will be removed.

This way we can add css classes dynamically using 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...

AngularJS Blur Directive

There is no direct support for blur event in AngularJs. But we can add support for blur event by creating directive.

Add the following directive to your javascript file

app.directive('ngBlur', ['$parse', function($parse) {
  return function(scope, element, attr) {
    var fn = $parse(attr['ngBlur']);
    element.bind('blur', function(event) {
      scope.$apply(function() {
        fn(scope, {$event:event});
      });
    });
  }
}]);

Then use it in your html template like below

<input type="text" ng-blur="myFunc()"/>

And write the function myFunc() in your controller

$scope.myFunc = function(){
   alert("hello!!");
}

Hope this helps you.

For more posts on AngularJs visit: http://coding-issues.blogspot.in/search/label/angularJS

Read more...