ng-model绑定在控制器中返回undefined问题排查求助
解决AngularJS中ng-model绑定后返回undefined的问题
嘿,我帮你排查下这个问题——你遇到的控制台打印返回undefined的情况,几乎可以肯定是AngularJS的原型继承机制导致的,这是新手常踩的坑!
问题根源
AngularJS里,像<form>、<ion-view>这类指令会创建子作用域。当你直接把ng-model绑定到$scope上的原始类型属性(比如$scope.name、$scope.distance)时,子作用域会创建一个同名的新属性来存储用户输入,而不是修改父控制器中$scope的属性。这就导致你在控制器的createGoal函数里访问$scope.name时,拿到的是父作用域的初始值(undefined),而非用户输入的内容。
解决方案:用"对象.属性"的方式绑定ng-model
AngularJS的原型继承在处理对象属性时会沿着作用链查找,不会创建新属性,所以我们需要把所有绑定的属性放到一个对象里,而不是直接挂在$scope上。
步骤1:修改控制器代码
先在控制器里初始化一个用于存储表单数据的对象,比如$scope.formData,然后在createGoal里直接使用这个对象的属性:
.controller("GoalFormCtrl", function($scope, $state, $stateParams) { // 初始化表单数据对象 $scope.formData = {}; $scope.createGoal = function() { $scope.goal = { name: $scope.formData.name, distance: $scope.formData.distance, startDate: $scope.formData.startDate, recurrent: $scope.formData.recurrent // 关联重复选项状态 }; console.log($scope.goal); // 现在就能拿到正确的值了! }; })
步骤2:修改HTML中的ng-model绑定
把所有ng-model改成formData.xxx的形式,同时修复你代码里的小问题(比如finishDate的input缺失ng-model):
<ion-view view-title="Create Goal"> <ion-content> <form style="margin-top:25px"> <!-- 目标名称输入 --> <div class="content double-padding" style="padding-bottom:0px"> <h4 class="positive">{{ "_goal_name" | translate }}</h4> <input type="text" ng-model="formData.name" style="border-bottom:1px solid grey;font-size:20px;margin-left:0px;width:100%"> </div> <!-- 目标距离输入 --> <div class="content double-padding" style="padding-bottom:0px"> <h4 class="positive">{{ "_goal_distance" | translate }}</h4> <input type="text" ng-model="formData.distance" style="border-bottom:1px solid grey;font-size:20px;margin-left:0px;width:100%"> </div> <!-- 开始日期输入 --> <div class="content double-padding" style="padding-bottom:0px"> <h4 class="positive">{{ "_goal_startDate" | translate }}</h4> <input type="text" ng-model="formData.startDate" style="border-bottom:1px solid grey;font-size:20px;margin-left:0px;width:100%"> </div> <!-- 结束日期输入(仅当recurrent为true时显示) --> <div ng-show="formData.recurrent" class="content double-padding" style="padding-bottom:0px"> <h4 class="positive">{{ "_goal_finishDate" | translate }}</h4> <input type="text" ng-model="formData.finishDate" style="border-bottom:1px solid grey;font-size:20px;margin-left:0px;width:100%"> </div> <!-- 重复选项开关 --> <ion-toggle ng-model="formData.recurrent" toggle-class="toggle-positive"> <h4 class="positive" style="font-size:18px;">{{ "_goal_recurrence" | translate }}</h4> </ion-toggle> <!-- 创建按钮 --> <div class="content double-padding" style="padding-bottom:0px"> <button ng-click="createGoal()" class="button button-positive button-block">{{ "_button_create" | translate }}</button> </div> </form> </ion-content> </ion-view>
额外说明
- 我帮你补全了
finishDate输入框的ng-model,不然这个值也会无法获取 - 把注释掉的
ion-toggle改成了绑定formData.recurrent,这样ng-show就能正确关联开关状态
这样修改后,你再点击创建按钮,控制台就能打印出正确的用户输入值了!
内容的提问来源于stack exchange,提问作者Dana Alexandra Llamas
相关产品推荐
相关产品推荐

