ng-blur不会在父元素上触发

时间:2014-09-20 21:41:12

标签: javascript html angularjs dom angularjs-directive

我正在尝试在<tr ng-blur="blurFn()">上使用ng-blur,但它不会触发。它仅在子<input>元素上触发。

这不是<tr><td>特有的。根据Angular documentationng-blurblur event作出反应,而fiddle没有“冒泡”。 “聚焦”事件泡沫,但没有ng-focusout。

我是否遗漏了某些内容或是否需要创建新的指令来处理焦点事件?

以下是代码段和{{3}}:

HTML

<div ng-app="App">
    <div ng-controller="Ctrl as ctrl">
        <table>
            <tr ng-repeat="item in ctrl.items" ng-blur="ctrl.blurFn()">
                <td><input ng-model="item.A"/></td>
                <td><input ng-model="item.B"/></td>
            </tr>
        </table>
    </div>
</div>

JS

angular.module("App", [])
.controller("Ctrl", function(){
    this.blurFn = function($event){
        console.log($event.target);
    };

    this.items = [
        {A: "111", B: "222"},
        {A: "111", B: "222"},
        {A: "111", B: "222"},
        {A: "111", B: "222"},
        {A: "111", B: "222"}
        ];
});

1 个答案:

答案 0 :(得分:3)

一种方法就是创建自己的焦点指示。

angular.module("App", [])
.controller("Ctrl", function(){
    this.blurFn = function($event){
        console.log("Yay, blurred");
        this.name = "focessed out at" + $event.target.name;
    };
    
    this.items = [
        {A: "111", B: "222"},
        {A: "111", B: "222"},
        {A: "111", B: "222"},
        {A: "111", B: "222"},
        {A: "111", B: "222"}
        ];
//This is just the way other handlers are defined...
}).directive('focusout', ['$parse', function($parse) {
      return {
        compile: function($element, attr) {
          var fn = $parse(attr.focusout);
          return function handler(scope, element) {
            element.on('focusout', function(event) {
              scope.$apply(function() {
                 fn(scope, {$event:event});
              });
            });
          };
        }
      };
}]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<div ng-app="App">
    
    <div ng-controller="Ctrl as ctrl">
        {{ctrl.name}}
        <table>
            <tr ng-repeat="item in ctrl.items" focusout="ctrl.blurFn($event)">
                <td><input ng-attr-name="A{{$index}}" ng-model="item.A"/></td>
                <td><input ng-attr-name="B{{$index}}" ng-model="item.B"/></td>
            </tr>
        </table>
    </div>
</div>

您可能想知道firefox中不支持focusout事件。