Shashi Shashi - 3 months ago 37
AngularJS Question

angular directive highlight if any of inputs in div has focus

I have created an angular directive for a repeatable section with form elements
I want the whole section/div to be highlighted when any of then input fields inside the div are in focus

template.html

<div class="col-md-12 employee-section">
<label for="name_{{$index}}">Name</label>
<input type="text" id="name_{{$index}}" class="col-md-6" ng-model="model.name"/>

<label for="address_{{$index}}">Address</label>
<input type="text" id="address_{{$index}}" class="col-md-6" ng-model="model.address"/>
</div>


directive

angular.module('test').directive('employee' , function(){
return {
link: function(scope, element){
},
restrict: 'AE',
scope: {
model: "="
},
templateUrl: 'template.html'
};
}


controller

angular.module('test').controller('employeeCtrl' , function($scope){
$scope.employees = [{name:'Jackk',address:'Main st'}, {name:'Jill',address:'Main st 123'}
});


html page

<div ng-repeat="employee in employees>
<employee model="employee"></employee>
</div>

Answer

Here's the directive which I was looking for with link for Plnkr

app.directive('ngFocusModel', function () {
    return function (scope, element) {

      var focusListener = function () {
          scope.hasFocus = true;
          scope.$digest();
      };

      var blurListener = function () {
          scope.hasFocus = false;
          scope.$digest();
      };


      element[0].addEventListener('focus', focusListener, true);
      element[0].addEventListener('blur', blurListener, true);
   };
});