Angularjs访问动态元素的范围

时间:2016-09-05 05:44:14

标签: angularjs dynamic scope angular-ng-if

我有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

如果所选的收音机的值是&#34; FIXED&#34;,则使用ng-if显示另一个文本字段。此文本字段包含&#39; required&#39;验证

<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的值,因为当我点击值为city的单选按钮时,动态显示输入FIXED

如果我使用ng-show代替ng-if,我会在控制器中获得$scope.city变量值,但在这种情况下,即使我选择单选按钮{ {1}}。当我选择单选按钮ANYWHERE时,城市字段将被隐藏,其验证无效。

谁能过上我的一天:)

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

你试过ng-required="boolValueOrExpression"吗?在你的情况下,这是一个有条件的验证。