AngularJS - 属性指令输入值的变化 [英] AngularJS - Attribute directive input value change
问题描述
我有一个AngularJS属性的指令,我想采取行动的任何时间其父输入值发生变化。现在我用jQuery做的:
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:
angular.module("myDirective", [])
.directive("myDirective", function()
{
return {
restrict: "A",
scope:
{
myDirective: "=myDirective"
},
link: function(scope, element, attrs)
{
element.keypress(function()
{
// do stuff
});
}
};
});
有没有办法做到这一点没有jQuery的?我发现关键preSS事件是不是做什么我就想要,而我敢肯定,我会想出一个解决方案,我变得有点紧张,当我诉诸于使用jQuery角项目。
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.
那么,什么是应该做这个角的方式?
So what's the Angular way to do this?
推荐答案
这里有在AngularJS文档一个很好的例子:
There's a great example in the AngularJS docs here:
<一个href=\"http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController\">http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController
这是很好的评价,应该让你在正确的方向。
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:
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';
}
修改同样的事情,不需要 ngModel
( http://jsfiddle.net/mb98y/1/ ):
Edit Same thing, doesn't require ngModel
(http://jsfiddle.net/mb98y/1/):
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';
}
这篇关于AngularJS - 属性指令输入值的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!