[英]Accessing ng-model from controller getting undefined
I'm having an <input type="text" ng-model="authorid">
in my html, it gets automatically updated when user updates some other field in the form. 我的html中有一个<input type="text" ng-model="authorid">
,当用户更新表单中的其他字段时,它会自动更新。 It works fine in the html, however trying to access the authorid from the controller it always gets undefined 它在html中工作正常,但是尝试从控制器访问authorid时,它总是未定义
console.log($scope.authorid);
... any ideas please? ...有什么想法吗?
I have tried numerous solutions here and none worked, especially that I don't want to add another method to set it. 我在这里尝试了许多解决方案,但是都没有用,特别是我不想添加其他方法来设置它。 Any ideas please? 有什么想法吗?
After spending good number of hours trying to understand what's going on. 在花费大量时间尝试了解正在发生的事情之后。 I found the answer here: AngularJS update input manually does not trigger change in the model 我在这里找到了答案: 手动AngularJS更新输入不会触发模型更改
which basically led me to write the following code and that fixed it: 这基本上导致我编写了以下代码,并对其进行了修复:
var e = document.getElementById("field");
e.value = "my updated value";
var $e = angular.element(e);
$e.triggerHandler('input');
Thanks to @Fresheyeball and thanks everyone for trying help as well 感谢@Fresheyeball,也感谢大家也尽力提供帮助
You should follow best-practice, and make your `authorid' to a object.property variable. 您应该遵循最佳实践,并将您的“ authorid”设为object.property变量。
first, define in your controller, something like: 首先,在您的控制器中定义以下内容:
$scope.form = {};
then in your html, do: 然后在您的html中,执行以下操作:
<input type="text" ng-model="form.authorid">
This is because in AngularJS, a child scope normally prototypically inherits from its parent scope. 这是因为在AngularJS中,子作用域通常从其父作用域继承原型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.