[英](AngularJS Directive) Change model value on input blur
I have a ng-model input element where I would like to enter just integer, positive numbers, but in case of empty input set model value to "1". 我有一个ng-model输入元素,我想输入整数,正数,但在空输入的情况下,将模型值设置为“1”。
I have created a directive, but after input blur it does not change model value to "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;
});
}
};
});
Here is live JSFiddle example: http://jsfiddle.net/buh86w8n/2/ 这是JSFiddle的实例: http : //jsfiddle.net/buh86w8n/2/
Is there anyone who could help me? 有没有人可以帮助我?
elem.on('blur', function(){ // code..})
is out side angular scope. elem.on('blur', function(){ // code..})
是一个侧角范围。
To change scope value inside elem.on blur
event you have to call $apply()
. 要更改
elem.on blur
事件中的范围值,您必须调用$apply()
。
Here is working plunkr 这是工作的plunkr
elem.on blur event : elem.on模糊事件 :
elem.on('blur', function () {
var value = String(elem[0].value);
if (value.length == 0){
scope.item.qty = 1;
scope.$apply();
}
});
Or you can just $watch
for that input, if its empty set it on 1. 或者你可以只
$watch
那个输入,如果它的空白设置为1。
So it starts with 2, if u delete it it will be set to 1, else set it on any number. 所以它从2开始,如果你删除它,它将被设置为1,否则将其设置为任何数字。
Here is your code edited: 这是你的代码编辑:
http://jsfiddle.net/buh86w8n/4/ http://jsfiddle.net/buh86w8n/4/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.