可能是个愚蠢的问题,但我的 html 表单带有简单的输入和按钮:
<input type="text" ng-model="searchText" />
<button ng-click="check()">Check!</button>
{{ searchText }}
然后在 Controller 中(从routeProvider调用模板和 Controller ):
$scope.check = function () {
console.log($scope.searchText);
}
为什么在单击按钮时,我在控制台中看到 View 已正确更新但未定义?
谢谢!
更新:
好像我实际上已经解决了这个问题(之前不得不想出一些解决方法):
只需将我的属性名称从 searchText
更改为 search.text
,然后在 Controller 中定义空的 $scope.search = {};
对象瞧……不知道为什么它会起作用;]
最佳答案
“如果你使用 ng-model,你必须有一个点。”
让你的模型指向一个 object.property,然后你就可以开始了。
Controller
$scope.formData = {};
$scope.check = function () {
console.log($scope.formData.searchText.$modelValue); //works
}
模板
<input ng-model="formData.searchText"/>
<button ng-click="check()">Check!</button>
当子作用域在起作用时会发生这种情况 - 例如子路由或 ng-repeats。
子作用域创建它自己的值并产生名称冲突 as illustrated here :
更多信息请观看此视频:https://www.youtube.com/watch?v=SBwoFkRjZvE&t=3m15s
关于javascript - ng-model 不更新 Controller 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12618342/