What's the problem with your code?
The issue lies in the logical aspect. The condition ng-if="studentType"
is used to display the input container, but within the change event,
if (value.studentType = "angularjs")
is utilized. This does not check a condition; rather, it performs an assignment operation. It should be written as
if (value.studentType == "angularjs")
or
if (value.studentType === "angularjs")
to compare the value of
value.studentType
with the string
"angularjs"
. In the current setup, the if statement will always assign
"angularjs"
to
studentType
, followed by assigning
"false"
to
studentType
inside the if block. This process is unnecessary.
There are multiple ways to resolve this issue. I recommend two options:
Working Demo
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
// $scope.showInput = true;
// $scope.getOption = function (value) {
// if (value.studentType == "angularjs") {
// $scope.showInput = false;
// }
// };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div>
<p>Course Type</p>
<div>
<select name="student-type" id="student-type" class="icon-select-down" ng-model="studentType"
ng-change="getOption(this)">
<option value="java" selected>Java</option>
<option value="angularjs">Angular js</option>
<option value="reactJs">React js</option>
</select>
</div>
</div>
<div ng-if="studentType !== 'angularjs'">
<p>Attendance Days</p>
<div class="slice-item">
<input type="text" class="input input-text" ng-model="attendanceDays" required validate-on="blur"
ng-pattern="/^([1-9]|10)$/" invalid-message="'You must enter a number between 1 and 25'" />
</div>
</div>
</div>
- Option 2: Within the change function, evaluate the selected option's value and set a visibility boolean accordingly. Adjust the input's visibility based on that boolean.
Working Demo
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.showInput = true;
$scope.getOption = function (value) {
$scope.showInput = value.studentType !== "angularjs";
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div>
<p>Course Type</p>
<div>
<select name="student-type" id="student-type" class="icon-select-down" ng-model="studentType"
ng-change="getOption(this)">
<option value="java" selected>Java</option>
<option value="angularjs">Angular js</option>
<option value="reactJs">React js</option>
</select>
</div>
</div>
<div ng-if="showInput">
<p>Attendance Days</p>
<div class="slice-item">
<input type="text" class="input input-text" ng-model="attendanceDays" required validate-on="blur"
ng-pattern="/^([1-9]|10)$/" invalid-message="'You must enter a number between 1 and 25'" />
</div>
</div>
</div>