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

标签 jquery angularjs attributes directive

我有一个 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 事件并没有完全按照我想要的方式执行,虽然我确信我会想出一个解决方案,但当我在 Angular 项目中使用 jQuery 时,我会有点紧张。

那么 Angular 的方法是什么?

最佳答案

AngularJS docs 中有一个很好的例子.

它的评论非常好,应该可以为您指明正确的方向。

一个简单的例子,也许更多的是你正在寻找的内容如下:

jsfiddle

<小时/>

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, element, attrs) {
            scope.$watch(attrs.ngModel, function (v) {
                console.log('value changed, new value is: ' + v);
            });
        }
    };
});

function x($scope) {
    $scope.test = 'value here';
}
<小时/> <小时/>

编辑:同样的事情,不需要ngModel jsfiddle :

JavaScript

angular.module('myDirective', [])
    .directive('myDirective', function () {
    return {
        restrict: 'A',
        scope: {
            myDirective: '='
        },
        link: function (scope, element, 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 - AngularJS - 属性指令输入值更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16308322/

相关文章:

javascript - 如何通过限制字符类型向 Ember.Textfield 值绑定(bind)添加验证?

javascript - 服务器不读取 Cordova FileTransfer 选项参数

javascript - 如何使用 AngularJS 将 list 中的值存储为对象中的数组?

python:在父类的方法中,调用该类的类方法,但绑定(bind)到子类

javascript - 拖动调整包含在另一个带有填充的 div 的大小

php - 就地编辑更新脚本安全性

jquery - Angular JS : Changing input value from jquery does not update ng-model

ios - 如何更新 CoreData 中另一个实体的子实体

javascript - TinyMCE,允许数据属性

javascript - 无法滚动到动态元素