简体   繁体   English

AngularJS指令在文本输入更改后运行

[英]AngularJS directive to run after text input changes

I am using a bootstrap calendar datepicker that operates and modifies an <input type="text"> element. 我正在使用引导日历datepicker,该日历操作并修改<input type="text">元素。

If I use ng-change="myAngularExpression()" it calls the function as soon as the text box is clicked. 如果我使用ng-change="myAngularExpression()"则在单击文本框后立即调用该函数。 How can I have the function call after the input actually changes? 输入实际更改 ,如何调用函数?

In my specific case, a user clicks in the text box that is displaying MM/DD/YYYY and a dropdown calendar comes down, then the angular expression executes, then the user changes the value and nothing happens until they click off the element and back on it. 在我的特定情况下,用户单击显示MM / DD / YYYY的文本框,然后出现一个下拉日历,然后执行角度表达式,然后用户更改该值,直到单击元素并返回时什么都没有发生在上面。

I'm assuming you're using a jQuery-based Bootstrap datepicker. 我假设您正在使用基于jQuery的Bootstrap datepicker。 Unfortunately, mixing jQuery-based Bootstrap widgets with Angular rarely works out well. 不幸的是,很少将基于jQuery的Bootstrap小部件与Angular混合使用。

The better alternative is to use UI Bootstrap , which is a collection of Bootstrap widgets written entirely in Angular. 更好的选择是使用UI Bootstrap ,它是完全用Angular编写的Bootstrap小部件的集合。 For example, here's a datepicker . 例如,这是一个datepicker

Once you're using Angular for your widgets (with UI Bootstrap), watching for changes to your date becomes as simple as $scope.$watch() : 一旦将Angular用于窗口小部件(通过UI Bootstrap),监视日期的更改就变得像$scope.$watch()一样简单:

$scope.$watch('date', function() { /* ... */ });

Full example: 完整示例:

 var app = angular.module('app', ['ui.bootstrap']); app.controller('Main', function($scope) { $scope.date = new Date(); // watch date for changes $scope.$watch('date', function(newValue, oldValue) { if (newValue !== oldValue) { $scope.message = 'Date changed from ' + oldValue + ' to ' + newValue; } }); }); 
 <div ng-app="app"> <div ng-controller="Main"> <datepicker ng-model="date"></datepicker> <div ng-bind="message"></div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.0/ui-bootstrap-tpls.min.js"></script> 

Someone may be able to provide an answer that allows the jQuery-based datepicker to work "good enough" with Angular, but that's a slippery road. 也许有人可以提供一个答案,使基于jQuery的datepicker可以与Angular一起“足够好”地工作,但这是一条湿滑的道路。

How about ng-keydown ? ng-keydown呢? This way the input will change only when you press your key down on it. 这样,只有在您按下按键时输入才会改变。

<input ng-keydown='someAwesomeMethodHere()'/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM