您的位置:首页 > Web前端 > AngularJS

AngularJS ng-if ng-repeat下使用ng-model

2015-07-28 14:58 801 查看
因为ng-if, ng-repeat 会创建新的scope, 在ng-if 内使用ng-model, 需要加上$parent, 例如:$parent,.newVal, 才能在全局的scope中用$scope.newVal访问。

实例如下:

HTML 文件:

<pre name="code" class="html">
<pre name="code" class="html"> <div class="col-lg-8" ng-init="isShow = true">
<input type="text" class="form-control input-checkbox" id="inputTest" ng-model="newVal" ng-if="isShow" >
<input type="button" value="test" ng-click="getVal()" />
</div><span style="font-family: Arial, Helvetica, sans-serif;">                          	</span>




JS 文件:

$scope.getVal = function(){
console.log($scope.newVal);
}

在text框中输入值test, 点击button, 输出为 : undefined

该ng-model 为$parent.newVal: 

<div class="col-lg-8" ng-init="isShow = true">
<input type="text" class="form-control input-checkbox" id="inputTest"
ng-model="$parent.newVal" ng-if="isShow" >
<input type="button" value="test" ng-click="getVal()" />
</div>

在text框中输入值test, 点击button, 输出为:test

所以在ng-if 内使用ng-model, 需要加上$parent, 例如:$parent,.newVal, 才能在全局的scope中用$scope.newVal访问。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: