gpt4 book ai didi

javascript - (AngularJS 指令)在输入模糊时更改模型值

转载 作者:行者123 更新时间:2023-11-30 12:16:17 26 4
gpt4 key购买 nike

我有一个 ng-model 输入元素,我想在其中输入整数、正数,但如果输入为空,则将模型值设置为“1”。

我创建了一个指令,但在输入模糊后它不会将模型值更改为“1”:

angular.module('myapp', [])
.controller('MainCtrl', function ($scope) {
$scope.item = { qty: 2 };
})
.directive('cartQty', function () {
return {
require: 'ngModel',
link: function (scope, elem) {
scope.$watch('item.qty', function (newValue, oldValue) {
var arr = String(newValue).split('');
if (arr.length == 0) return;
if (newValue == 0) scope.item.qty = 1;
if (isNaN(newValue)) scope.item.qty = oldValue;
});
elem.on('blur', function () {
var value = String(elem[0].value);
if (value.length == 0) scope.item.qty = 1;
});
}
};
});

这是实时 JSFiddle 示例:http://jsfiddle.net/buh86w8n/2/

有没有人可以帮助我?

最佳答案

elem.on('blur', function(){//code..}) 超出了 Angular 范围。

要在 elem.on blur 事件中更改范围值,您必须调用 $apply()

这里是 working plunkr

elem.on 模糊事件:

elem.on('blur', function () {
var value = String(elem[0].value);
if (value.length == 0){
scope.item.qty = 1;
scope.$apply();
}
});

关于javascript - (AngularJS 指令)在输入模糊时更改模型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32348043/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com