Angularjs 访问动态元素的范围
Angularjs accessing scope for dynamic elements
我有 2 个无线电输入字段
<input type="radio" name="location_type" ng-model="location_type" value="ANYWHERE" required> Anywhere
<input type="radio" name="location_type" ng-model="location_type" value="FIXED" required> Fixed
如果 selected radio 的值为 "FIXED",则使用 ng-if 显示另一个文本字段。此文本字段有 'required' 验证。
<div ng-if="location_type == 'FIXED'">
<input type="text" class="form-control" name="city" ng-model="city" placeholder="Enter City" ng-blur="cname=''" ng-focus="cname='bold'" required>
</div
我没有在控制器中获得 $scope.city
的值,因为当我单击值为 FIXED
的单选按钮时,输入 city
会动态显示。
如果我使用 ng-show
而不是 ng-if
,我会在控制器中获得 $scope.city
变量值,但在这种情况下,即使我 select 单选按钮 ANYWHERE
。当我 select 单选按钮 ANYWHERE
.
时,城市字段将被隐藏并且其验证不需要工作
谁能让我开心:)
你试过了吗ng-required="boolValueOrExpression"
?在您的情况下,这是有条件的验证。
ng-if
指令 create new child scope
.
根据您的 html,您正在将 city
分配给此 child scope
而不是作为您的控制器的父范围。
所以,无法在控制器中访问。
所以,你需要做这样的事情。
像这样在父控制器中声明对象;
$scope.parentObj = {};
并改变你的 html ;
<input type="text" class="form-control" name="city" ng-model="parentObj" required>
现在,您的子作用域将从控制器获取继承对象 属性;
因此,它将反映在控制器中。
这是工作Plunker
我有 2 个无线电输入字段
<input type="radio" name="location_type" ng-model="location_type" value="ANYWHERE" required> Anywhere
<input type="radio" name="location_type" ng-model="location_type" value="FIXED" required> Fixed
如果 selected radio 的值为 "FIXED",则使用 ng-if 显示另一个文本字段。此文本字段有 'required' 验证。
<div ng-if="location_type == 'FIXED'">
<input type="text" class="form-control" name="city" ng-model="city" placeholder="Enter City" ng-blur="cname=''" ng-focus="cname='bold'" required>
</div
我没有在控制器中获得 $scope.city
的值,因为当我单击值为 FIXED
的单选按钮时,输入 city
会动态显示。
如果我使用 ng-show
而不是 ng-if
,我会在控制器中获得 $scope.city
变量值,但在这种情况下,即使我 select 单选按钮 ANYWHERE
。当我 select 单选按钮 ANYWHERE
.
谁能让我开心:)
你试过了吗ng-required="boolValueOrExpression"
?在您的情况下,这是有条件的验证。
ng-if
指令 create new child scope
.
根据您的 html,您正在将 city
分配给此 child scope
而不是作为您的控制器的父范围。
所以,无法在控制器中访问。
所以,你需要做这样的事情。
像这样在父控制器中声明对象;
$scope.parentObj = {};
并改变你的 html ;
<input type="text" class="form-control" name="city" ng-model="parentObj" required>
现在,您的子作用域将从控制器获取继承对象 属性;
因此,它将反映在控制器中。
这是工作Plunker