javascriptangularjsangularjs-directivemodel-bindingangular-data

Call a event after binding model to textbox - Angular


I want to implement a event something like binding-completed for every textbox (input) in my application.

Here I am trying to add a CSS class on some condition in onblur event. Thats fine. But I wan't to execute the same function after binding some model to the textbox.

  var app = angular.module("main", []);

  var MainController = function($scope, $http) {
    $scope.message = "CSS Change";
  };
  app.directive('floatBox', ['$document', '$timeout', '$rootScope', function($document, $timeout, $rootScope) {
    return {
      restrict: 'A',
      scope: true,
      link: function(scope, element, attr) {
        //this is not for validation, this is just a sample for what I want to do.
        //Please don't suggest Angular validations.
        element.on('blur', function(event) {
          changeCSSClass(element);
        });

        function changeCSSClass(element) {
          if (element.val().length == 0) {
            element.addClass('red');
            element.removeClass('green');

          } else {
            element.addClass('green');
            element.removeClass('red');
          }
        }
      }
    };
  }]);

HTML:

<div ng-controller="MainController">
  <input float-box type="text" ng-model="message">
 </div>

CSS:

.red {
   border: 5px solid red;
}

.green {
   border: 5px solid green;
}

I want to call the changeCSSClass after some value has came to my textbox.

Please use the pluk for quick editing : http://plnkr.co/edit/NTjcV4KDHRVZasoCJz6l?p=preview

Base Problem: When I blur from textbox the event works fines. But I want to show the color in the initial load itself, ie after binding the modal message to textbox. So that I will get the textbox length and based on that I can set the css class

I don't want to use ng-class in all textbox and use a scope, rather a common implementation is required.


Solution

  • You can bind your data to your directive, and use $watch :

    Directive

    (function(){
    
      function directive(){
        return {
          restrict: 'A',
          link: function(scope, element, attr) {
            //this is not for validation, this is just a sample for what I want to do.
            //Please don't suggest Angular validations
    
            scope.$watch(attr.ngModel, function(){
                  changeCSSClass(element);
            });
    
            function changeCSSClass(data) {
              if (data.length == 0) {
                element.addClass('red');
                element.removeClass('green');
              } else {
                element.addClass('green');
                element.removeClass('red');
              }
            }
          }
        };
    };
    
    angular
      .module('app')
      .directive('floatBox', directive);
    
    
    })();
    

    HTML

    <input float-box type="text" ng-model="message">