我有一个 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 中有一个很好的例子.
它的评论非常好,应该可以为您指明正确的方向。
一个简单的例子,也许更多的是你正在寻找的内容如下:
<小时/>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/