Fabrizio A Fabrizio A - 21 days ago 6
AngularJS Question

AngularJS $scope.$watch a property ngModel of a select input

I've an AngularJS app with a form generated by a python backend. My problem is to trigger a specific function (listener) when the ngModel of a select input change:

here the rendered html code:

<select id="id_vehicle" name="vehicle" ng-model="contract.vehicle" class="ng-valid ng-valid-parse ng-dirty ng-touched">
<option value="" selected="selected">---------</option>
<option value="1">Qashqai</option>
<option value="2">X6</option>
</select>


here my Angular code:

contract_form_app.controller("mainCtrl", ['$scope', '$http', '$location', '$window', 'djangoForm', function($scope, $http, $location, $window, djangoForm) {

$scope.contract = {
vehicle: ""
};

function loadVehicleInformation(oldValue, newValue) {
// This only triggered one time !!!!.
console.log("Selected vehicle " + $scope.contract.vehicle);
};

$scope.$watch('contract.vehicle', loadVehicleInformation());


When I select another option on my select input, my listener function doesn't trigger... why?

ps: When the page has been loaded, the contract object will have a lot of others fields.

Answer

I recommend you use ng-change instead of a watch on the controller if you're looking to trigger a function when that value changes, that's what ng-change is for.

<select id="id_vehicle" name="vehicle" ng-change="loadVehicleInformation()" ng-model="contract.vehicle" class="ng-valid ng-valid-parse ng-dirty ng-touched">
    <option value="" selected="selected">---------</option>
    <option value="1">Qashqai</option>
    <option value="2">X6</option>
</select>
Comments