解決方案1:
只需使用ng-show
代替ng-if
。因爲ng-if在這裏創建一個新的範圍。
<div ng-controller="helloController">
<h1>{{hello}}</h1>
<form name="createForm">
<div ng-show="providerMediumType != 'XML_API'">
<input name="cSep" ng-model="cSep" type="text" class="form-control" allow-tab required ng-maxlength="10" />
<p ng-show="createForm.cSep.$invalid && !createForm.cSep.$pristine" class="error">Column separator required (1-10 characters)</p>
</div>
<input type="button" ng-disabled="createForm.$invalid" value="Go" />
</form>
</div>
Demo link
解決方案2:
或只是拉輸入轉場到裏面DIV標籤
Demo link2
<div ng-controller="helloController">
<h1>{{hello}}</h1>
<form name="createForm">
<div ng-if="providerMediumType != 'XML_API'">
<input name="cSep" ng-model="cSep" type="text" class="form-control" allow-tab required ng-maxlength="10" />
<p ng-show="createForm.cSep.$invalid && !createForm.cSep.$pristine" class="error">Column separator required (1-10 characters)</p>
<input type="button" ng-disabled="createForm.$invalid" value="Go" />
</div>
</form>
</div>
解決方案3:
使用controller as
語法來實現此目的。 helloController中的小改動。請注意,this.providerMediumType
而不是$scope.providerMediumType
。
<body ng-app="HelloApp">
<div ng-controller="helloController as vm">
<h1>{{hello}}</h1>
<form name="createForm" method="POST" action="/form.php">
<div ng-if="vm.providerMediumType != 'XML_API'">
<input name="cSep" ng-model="vm.cSep" type="text" class="form-control" allow-tab required ng-maxlength="10" />
<p ng-show="createForm.cSep.$invalid && !createForm.cSep.$pristine" class="error">Column separator required (1-10 characters)</p>
</div>
<input type="submit" ng-disabled="createForm.$invalid" value="Go" />
</form>
</div>
</body>
angular.module('HelloApp', ['components']).controller('helloController',helloController);
function helloController($scope) {
$scope.hello = 'Hello Me!';
this.providerMediumType = 'XML_API';
}
Demo with ng-if
希望你注意到,即使在退格時它仍然是「假」,你按下'createForm。$ invalid'的時刻也變爲'false'。 –