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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16308322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:54:31  来源:igfitidea点击:

AngularJS - Attribute directive input value change

jqueryangularjsattributesdirective

提问by Mike Pateras

I've got an AngularJS attribute directive, and I would like to take an action any time its parent input's value changes. Right now I'm doing it with jQuery:

我有一个 AngularJS 属性指令,我想在其父输入的值发生变化时采取任何措施。现在我正在用 jQuery 做这件事:

angular.module("myDirective", [])
.directive("myDirective", function()
{
    return {
        restrict: "A",
        scope:
        {
            myDirective: "=myDirective"
        },
        link: function(scope, element, attrs)
        {
            element.keypress(function()
            {
                // do stuff
            });
        }
    };
});

Is there a way to do this without jQuery? I'm finding the keyPress event isn't doing exactly what I want it to, and while I'm sure I'll come up with a solution, I get a little nervous when I resort to using jQuery in an Angular project.

有没有办法在没有 jQuery 的情况下做到这一点?我发现 keyPress 事件并没有完全按照我的意愿去做,虽然我确定我会想出一个解决方案,但当我在 Angular 项目中使用 jQuery 时,我有点紧张。

So what's the Angular way to do this?

那么 Angular 的方法是什么?

回答by Langdon

There's a great example in the AngularJS docs.

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

It's very well commented and should get you pointed in the right direction.

它的评论很好,应该让你指向正确的方向。

A simple example, maybe more so what you're looking for is below:

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

jsfiddle

提琴手



HTML

HTML

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


JavaScript

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';
}




Edit:Same thing, doesn't require ngModeljsfiddle:

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

JavaScript

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';
}

回答by Jmr

Since this must have an input element as a parent, you could just use

由于这必须有一个输入元素作为父元素,因此您可以使用

<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">

Alternatively, you could use the ngModelControllerand add a function to $formatters, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

或者,您可以使用ngModelController和 添加一个函数到$formatters,它在输入更改时执行函数。请参阅http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

.directive("myDirective", function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, ngModel) {
      ngModel.$formatters.push(function(value) {
        // Do stuff here, and return the formatted value.
      });
  };
};

回答by Shivam

To watch out the runtime changes in value of a custom directive, use $observemethod of attrsobject, instead of putting $watchinside a custom directive. Here is the documentation for the same ... $observe docs

要注意自定义指令值的运行时更改,请使用object 的$observe方法attrs,而不是放入$watch自定义指令中。这是相同的文档... $observe docs