[英]How to pass ng-model as parameter to controller
How can i pass the ng-model with it's value as a parameter to a function in a controller from html.I tried to pass the ng-model as string to the controller but it didn;t works can anyone tell me how to do it. 我怎样才能将ng-model的值作为参数从html传递给控制器中的函数。我试图将ng-model作为字符串传递给控制器,但没有成功;任何人都不能告诉我该怎么做。
Html: HTML:
<input stopccp decimalpoint
ng-model="vm.product.rate"
placeholder="0"
type="number"
ng-change="vm.fillStarted()"
maxlength="5"
ng-keydown="vm.checkMaxLength(5, vm.product.rate)"
ng-click= "vm.hideScrollContent()"/>
Controller: 控制器:
var vm = this;
function checkMaxLength (maxLength, model) {
$log.log('checkMaxLength got called', maxLength);
$log.log('model is', model);
$log.log('model value', model.value);
// if (vm.product.rate.length === maxLength) {
// vm.product.rate.value = vm.product.rate.value.slice(0, -1);
// }
}
Logs: 日志:
checkMaxLength got called 5
model is
model value undefined
Your code is working as expected. 您的代码按预期工作。 As you are calling method on
ng-keydown
first time you will not see any value. 第一次在
ng-keydown
上调用method时,您将看不到任何值。 For second input you should see the first input value 对于第二个输入,您应该看到第一个输入值
<input stopccp decimalpoint
ng-model="vm.product.rate"
placeholder="0"
type="number"
ng-change="vm.fillStarted()"
maxlength="5"
ng-keydown="vm.checkMaxLength(5, vm.product.rate)"
ng-click= "vm.hideScrollContent()"/>
function checkMaxLength (maxLength, model) {
$log.log('checkMaxLength got called', maxLength);
$log.log('model is', model);//enter 123 in input. You should see 12 here
$log.log('model value', model.value);// It is wrong as model.value will always
be undefined
}
Use ng-keyup instead you ng-keydown to see typed input in log.
使用ng-keyup代替ng-keydown可以在日志中查看输入的内容。
Your code looks totally fine, i guess the issue lies here 您的代码看起来很好,我想问题出在这里
var vm = this; var vm = this;
and then you need to assign value to the product , otherwise it will be undefined. 然后您需要为产品分配值,否则它将是不确定的。
this.product = {};
var vm = this;
You should be able to access it simply within the controller
. 您应该能够简单地在
controller
访问它。
So change your ng-keydown
into: 因此,将您的
ng-keydown
更改为:
ng-keydown="vm.checkMaxLength(5)"
And then inside your checkMaxLength
function simply use: 然后在您的
checkMaxLength
函数内部,只需使用:
function checkMaxLength (maxLength) {
$log.log('checkMaxLength got called', maxLength);
$log.log('model is', vm.product.rate);
}
And of course inside the controller you should have your product object init: 当然,在控制器内部,您应该将产品对象初始化:
vm.product = {};
in order to use its rate
property as model 为了使用其
rate
属性作为模型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.