Angular.js:当输入处于焦点时设置CSS

时间:2013-10-09 16:04:52

标签: angularjs

有人知道如何进行以下工作:

如果用户点击“名称” - 在DIV上将CSS Class设置为XYZ?

<div ng-class="???">Enter your Name here</div>

<input type="text" ng-model="user.name" required id="name"/>

版本:AngularJS v1.0.8

3 个答案:

答案 0 :(得分:27)

如果您使用的是Angular 1.2.x,请参阅ng-focusng-blur

<div ng-class="{xyz: focused}">Enter your name here</div>
<input type="text" ng-model="user.name" ng-init="focused = false" ng-focus="focused = true" ng-blur="focused = false" id="name" required>

如果您使用的是1.0.x版本,则没有什么能阻止您根据Angular 1.2.x's定义自己的focusblur指令:

/*
 * A directive that allows creation of custom onclick handlers that are defined as angular
 * expressions and are compiled and executed within the current scope.
 *
 * Events that are handled via these handler are always configured not to propagate further.
 */
var ngEventDirectives = {};
forEach(
  'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  function(name) {
    var directiveName = directiveNormalize('ng-' + name);
    ngEventDirectives[directiveName] = ['$parse', function($parse) {
      return function(scope, element, attr) {
        var fn = $parse(attr[directiveName]);
        element.on(lowercase(name), function(event) {
          scope.$apply(function() {
            fn(scope, {$event:event});
          });
        });
      };
    }];
  }
);

答案 1 :(得分:7)

只需使用此指令:

app.directive('ngFocusClass', function () {
  return ({
        restrict: 'A',
        link: function(scope, element) {
            element.focus(function () {
                element.addClass('focus');
            });
            element.blur(function () {
                element.removeClass('focus');
            });
        }
    });
});

答案 2 :(得分:2)

pre-.2.xxx版本的工作示例:http://jsfiddle.net/atXAC/

在此示例中,ng-customblur指令将在控制器中触发function()。

HTML:

<div ng-controller="MyCtrl">
  <div ng-class="{'active':hasFocus==true,'inactive':hasFocus==false}">Enter your Name here</div>
  <input type="text" ng-model="user.name" ng-click="hasFocus=true" ng-customblur="onBlur()" required id="name"/>
</div>

JS:

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

function MyCtrl($scope) {
    $scope.onBlur = function(){        
        $scope.hasFocus = false;
    }
}