Dev Wadhwa Dev Wadhwa - 2 months ago 15
AngularJS Question

How can I make ng-change to work for same values as well?

I am new to

AngularJs
. My problem is : I have a dropdown box and a textbox. I am selecting some value from the dropdown box and
ng-change
fires and also the dropdown box get to its default value when some one starts typing in the textbox. Now after reset the dropdown if I again select the same value in dropdown which I selected previously then
ng-change
not get fired.

I used
ng-click
also for this but it doesnt work in all browsers then. I am stuck with this problem.

So is there any way make
ng-change
to work on the same value as the previous one or some alternative?

Any help or solution will be greatly appreciated. Thanks in advance.

My Code Snippet :

<code>
<input class="form-control" type="text" id="city1" onblur="codeAddress();" name="city1" ng-model="city1" required>
<select class="form-control" id="brandC" name="brandC" ng-model="vehicle.companyId" ng-change="selectServiceCenter();" required>
<option ng-selected="loginbrandId1==null" value='' >Select Your Car</option>
<option ng-selected="loginbrandId1 == vehicle.companyId" ng-repeat="vehicle in vehiclenames" value='{{vehicle.companyId}},{{vehicle.vehicleID}}' >{{vehicle.companyName}}--{{vehicle.vehicleNumber}}</option>
</select>
<script>
$scope.watchHitCountcity = 0;
$scope.$watch('city1', function (newValue, oldValue) {

if(newValue!=undefined)
{
document.getElementById("brandC").value= "";
}
$scope.watchHitCountcity++;
},true);
$scope.selectServiceCenter = function() {
alert("execute");
}
</script>
</code>

Answer

Reason behind your problem

What's happening in your case is you just removed the value from the dropdown using native java script document.getElementById("brandC").value= "";,but this doesn't change the value of ng-model of that element which is ng-model="vehicle.companyId".Because the ng-model of the dropdown has not changed the ng-change="selectServiceCenter();" function doesn't gets triggered as for angular still the ng-model is the same.

Solution

So change your below code like below as suggested by @Sandeep

$scope.vehicle ={}; //create vehicle object in scope..
$scope.$watch('city1', function (newValue, oldValue) {

        if(newValue!=undefined && newValue!=oldValue){
             $scope.vehicle.companyId = null;
            }
        $scope.watchHitCountcity++;
 },true);