我有一个使用angularJs的表单,问题末尾的所有代码都可以在我的plunker上找到。
我的控制器里面有
$scope.showTelfield= false; $scope.showEmailfield= false;
以我的形式以及电话领域和电子邮件字段使用:
ng-show="showTelField" ng-show="showEmailField"
如果用户从控制器内部设计的选项中选择它,则这些值应为true。
in html
<select class="form-control c-select" name="select" ng-model="feedback.myChannel" ng-options="channel.value as channel.label for channel in channels">
<option value="">Select a method</option>
</select>
控制器中的:
$scope.feedback = {
myChannel: "",
firstName: '',
lastName: '',
agree: false,
email: ''
};
$scope.channels = [{
value: "Tel",
label: "Tel"
}, {
value: "Email",
label: "Email"
}, {
value: "Tel & Email",
label: "Tel & Email"
}];
//Telling browser to view telephone or Email feild if needed..
if($scope.feedback.myChannel === "Tel" || $scope.feedback.myChannel === "Tel & Email"){
$scope.showTelField = true }
if($scope.feedback.myChannel === "Email" || $scope.feedback.myChannel === "Tel & Email"){
$scope.showEmailField = true }
$ scope.feedback.myChannel的值根据用户选择从空字符串更改为“Tel”,“Email”或“Tel&amp; Email”,并且我在一个额外的div中显示仅用于开发目的是确保他们改变用户的选择。
但是所有if语句都不起作用,尽管$ scope.feedback.myChannel的值根据我正在进行开发的显示div而变化。 任何想法为什么会这样?
你可以在我的plunker中看到我的代码 Here is my plunker
答案 0 :(得分:1)
首先,您的控制器中的ifs
只会在页面加载时被调用,之后angular
忽略它,除非您将逻辑置于{{ 1 {} function
。
要检测$scope
中的更改,您应该使用ngChange
指令,如下所示:
查看:强>
<select>
<强> JS:强>
<select ng-change="change()" class="form-control c-select" name="select" ng-model="feedback.myChannel" ng-options="channel.value as channel.label for channel in channels">
然后,您尝试用来操纵数据的变量($scope.change = function() {
console.log($scope.feedback.myChannel);
}
,showTelField
)可以简单地用指令替换, ie {{3} },所以你可以这样:
showEmailField
另外,我建议您在<div ng-switch="feedback.myChannel">
<div class="form-group " ng-class="{'has-error': !feedbackForm.telnum.$pristine && feedback.tel.number == '' || feedback.tel.areacode == ''}" ng-switch-when="Tel">
...
</div>
<div class="form-group has-feedback" ng-class="{'has-error': !feedbackForm.email.$pristine && feedback.email == '' || feedbackForm.email.$invalid }" ng-switch-when="Email">
...
</div>
<div ng-switch-when="Tel & Email">
...
</div>
</div>
的某些部分使用ngSwitch
指令代替ngShow
作为一种良好做法。
看看分叉的ngIf
。
答案 1 :(得分:0)
最好信任FormControl对象,方法是将ng-show="feedback.agree"
更改为ng-if="feedback.agree"
并选择字段required
:
<div class="col-sm-3 col-sm-offset-1" ng-if="feedback.agree">
<select class="form-control c-select" name="select" ng-model="feedback.myChannel" ng-options="channel.value as channel.label for channel in channels" required>
<option value="">Select a method</option>
</select>
<span class="help-block" ng-show="invalidChannelSelection && feedback.myChannel == ''">Select a method</span>
</div>
然后您可以根据表单的有效状态禁用提交按钮(我从|| invalidChannelSelection
指令中删除了ngDisabled
:
<button type="submit" class="btn btn-primary" name="submit" ng-disabled="feedbackForm.$invalid">Send Feedback</button>