0

I'm trying to fire an event when user finish typing into input field and I'm stuck at reading the value which was entered :(

Here is my code:

js

var subtitlesApp = angular.module('subtitlesApp', ['ngResource', 'ngCookies']);

subtitlesApp.directive('ngModelOnblur', function ($timeout) {
    return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, elm, attr) {
        elm.unbind('input').unbind('keydown').unbind('change');
    elm.bind('blur', function() {
            scope.$apply(function(imdb_id) {
            console.log(imdb_id)
                })
            });         
        }
    };
})

html

<input id="subtitle-imdb_id" type="text" ng-model="subtitle.imdb_id" ng-model-onblur/>

I'm getting:

a {$id: "004", this: a, $$listeners: Object, $parent: e, $$asyncQueue: Array[0]…}

Instead of getting the value of elm or imdb_id.

Thanks.

4

2 回答 2

1

您不应该取消绑定输入事件。您可以通过范围获取数据。

link: function (scope, elm, attr) {
    elm.unbind('keydown').unbind('change');
    elm.bind('blur', function () {
        scope.$apply(function (imdb_id) {
            console.log(scope.subtitle.imdb_id)
        })
    });
}
于 2013-09-11T20:28:43.197 回答
1

你得到的是一个范围,因为传递给方法 $apply 的第一个参数是当前范围。

如果要获取 的值ngModel,则必须调用$eval该范围,如:

link: function (scope, elm, attr) {
    elm.bind('blur', function() {
      scope.$apply(function(scope) {
        console.log(scope.$eval(attr.ngModel));
      });
    });         
    }
};

此外,宁可不要解除绑定事件。

于 2013-09-11T20:37:44.777 回答