AngularJS1中select的ng-model值控制器获取显示undefined求助
AngularJS Ionic中select绑定ng-model后控制器获取值为undefined的问题
我在Ionic项目中创建了一个select控件,用于选择人员并显示其对应信息,绑定到ng-model="cadLivroPreto"。页面上的{{cadLivroPreto.nome}}等表达式能正常显示选中人员的信息,但点击Cadastrar按钮后,控制器中console.log($scope.cadLivroPreto.nome)输出的却是undefined。
HTML代码
<ion-view view-title="Cadastro Livro Preto"> <ion-nav-buttons side="left"> </ion-nav-buttons> <ion-content> <div class="list card"> <select ng-model="cadLivroPreto" ng-options="y.nome for (x, y) in linkPessoasLoja"> </select> <label class="item item-input item-stacked-label"> <h3 ng-model=cadLivroPreto.nome>Nome: {{cadLivroPreto.nome}}</h3><br/> </label> <label class="item item-input item-stacked-label"> <h3 ng-model="cadLivroPreto.cpf">CPF: {{cadLivroPreto.cpf}}</h3><br/> </label> </div> <h3>teste: {{cadLivroPreto.id}}</h3><br/> <h3>teste: {{cadLivroPreto.nome}}</h3><br/> <!-- Acrescentar telefone --> </div> <button class = "button button-block button-dark" ng-click="Cadastrar()"> Cadastrar</button> </ion-content> </ion-view>
Controller代码
$scope.cadLivroPreto = {}; //$scope.pessoa = {}; $scope.Cadastrar = function(){ console.log($scope.cadLivroPreto.nome); console.log($scope.cadLivroPreto.cpf); };
问题原因分析
这是AngularJS作用域继承的典型问题:
- Ionic的
ion-view和ion-content指令会创建子作用域,当你在模板中直接把ng-model绑定到作用域的变量(比如cadLivroPreto)时,select选中选项后,子作用域会创建一个属于自己的cadLivroPreto变量,完全遮蔽了父作用域(控制器所在作用域)中的同名变量。 - 页面上的表达式能正常显示,是因为它们读取的是子作用域自己的
cadLivroPreto值;而控制器中的$scope.cadLivroPreto还是父作用域最初定义的空对象,所以访问其属性时会得到undefined。 - 另外要注意:
ng-model仅适用于表单控件(如input、select、textarea),你在<h3>标签上使用ng-model是无效的,属于多余代码。
解决方案
解决这个问题的核心是使用点语法,把ng-model绑定到一个父作用域对象的属性上,这样子作用域会通过原型链继承这个对象,修改属性时不会创建新的变量。具体步骤如下:
- 修改控制器代码:将
cadLivroPreto包裹在一个对象中,避免作用域遮蔽:
// 定义一个表单数据对象,避免作用域遮蔽 $scope.formData = { cadLivroPreto: {} }; $scope.Cadastrar = function(){ console.log($scope.formData.cadLivroPreto.nome); console.log($scope.formData.cadLivroPreto.cpf); };
- 修改模板代码:将所有
cadLivroPreto引用改为formData.cadLivroPreto,同时去掉<h3>标签上无效的ng-model:
<ion-view view-title="Cadastro Livro Preto"> <ion-nav-buttons side="left"> </ion-nav-buttons> <ion-content> <div class="list card"> <select ng-model="formData.cadLivroPreto" ng-options="y.nome for (x, y) in linkPessoasLoja"> </select> <label class="item item-input item-stacked-label"> <h3>Nome: {{formData.cadLivroPreto.nome}}</h3><br/> </label> <label class="item item-input item-stacked-label"> <h3>CPF: {{formData.cadLivroPreto.cpf}}</h3><br/> </label> </div> <h3>teste: {{formData.cadLivroPreto.id}}</h3><br/> <h3>teste: {{formData.cadLivroPreto.nome}}</h3><br/> <!-- Acrescentar telefone --> </div> <button class = "button button-block button-dark" ng-click="Cadastrar()"> Cadastrar</button> </ion-content> </ion-view>
这样修改后,子作用域中修改的是formData对象的cadLivroPreto属性,而formData是继承自父作用域的对象,所以控制器中能正确获取到选中的人员信息。
内容的提问来源于stack exchange,提问作者Lucas Santos
相关产品推荐
相关产品推荐

