9

有人知道如何使以下工作:

如果用户单击“名称”内部 - 在 DIV 上将 CSS 类设置为 XYZ ?

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

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

版本:AngularJS v1.0.8

4

3 回答 3

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定义自己的指令focus和指令:blur

/*
 * 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});
          });
        });
      };
    }];
  }
);
于 2013-10-09T16:11:00.357 回答
7

只需使用此指令:

app.directive('ngFocusClass', function () {
  return ({
        restrict: 'A',
        link: function(scope, element) {
            element.focus(function () {
                element.addClass('focus');
            });
            element.blur(function () {
                element.removeClass('focus');
            });
        }
    });
});
于 2015-01-11T09:30:14.403 回答
2

pre-1.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;
    }
} 
于 2013-10-09T17:03:14.067 回答