jquery – AngularJS – 属性指令输入值更改

我有一个AngularJS属性指令,我想采取一个行动,当它的父输入的值改变。现在我使用jQuery:
angular.module("myDirective",[])
.directive("myDirective",function()
{
    return {
        restrict: "A",scope:
        {
            myDirective: "=myDirective"
        },link: function(scope,element,attrs)
        {
            element.keypress(function()
            {
                // do stuff
            });
        }
    };
});

有没有办法这样做没有jQuery?我发现keyPress事件没有做我想要的,而我确定我会想出一个解决方案,当我诉诸使用jQuery在Angular项目时,有点紧张。

那么Angular的方法是什么呢?

解决方法

在AngularJS文档中有一个很好的例子:

http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

这是非常好的评论,应该让你指出正确的方向。

一个简单的例子,也许更多,你要找的是下面:

http://jsfiddle.net/mb98y/

HTML

<div ng-app="myDirective" ng-controller="x">
    <input type="text" ng-model="test" my-directive>
</div>

JavaScript

angular.module('myDirective',[])
    .directive('myDirective',function () {
    return {
        restrict: 'A',link: function (scope,attrs) {
            scope.$watch(attrs.ngModel,function (v) {
                console.log('value changed,new value is: ' + v);
            });
        }
    };
});

function x($scope) {
    $scope.test = 'value here';
}

编辑同样的事情,不需要ngModel(http://jsfiddle.net/mb98y/1/):

JavaScript:

angular.module('myDirective',scope: {
            myDirective: '='
        },attrs) {
            // set the initial value of the textBox
            element.val(scope.myDirective);
            element.data('old-value',scope.myDirective);

            // detect outside changes and update our input
            scope.$watch('myDirective',function (val) {
                element.val(scope.myDirective);
            });

            // on blur,update the value in scope
            element.bind('propertychange keyup paste',function (blurEvent) {
                if (element.data('old-value') != element.val()) {
                    console.log('value changed,new value is: ' + element.val());
                    scope.$apply(function () {
                        scope.myDirective = element.val();
                        element.data('old-value',element.val());
                    });
                }
            });
        }
    };
});

function x($scope) {
    $scope.test = 'value here';
}

相关文章

jQuery表单验证提交:前台验证一(图文+视频)
jQuery表单验证提交:前台验证二(图文+视频)
jQuery如何实时监听获取input输入框的值
JQuery怎么判断元素是否存在
jQuery如何实现定时重定向
jquery如何获取复选框选中的值