Jean Jean - 5 months ago 7
Javascript Question

Controller variable doesn't get displayed right in html

I'm trying to make a selection dropdown list from data extracted from database, in order to choose a certain date my html is :

<div>Select Year</div>
<select class="browser-default" data-ng-model="year">
<option ng-repeat="year in years">{{year}}</option>
<div>Select Month</div>
<select class="browser-default" data-ng-model="month" ng-options=" as for month in months" ></select>
<a class="btn waves-effect waves-light blue darken-1 right bout2" ng-click="changeDate(month, year)">Confirm</a>

and in my controller:

socket.emit('Question', {
// SQL to get the years from database
socket.on('response', function (data){

$scope.years =data.rep;
$scope.year = "2016";
$scope.list_months = {"months":[{"id":"01","name":"Janvier"},{"id":"02","name":"Fevrier"},{"id":"03","name":"Mars"},{"id":"04","name":"Avril"},{"id":"05","name":"Mai"},{"id":"06","name":"Juin"},{"id":"07","name":"Juillet"},{"id":"08","name":"Aout"},{"id":"09","name":"Septembre"},{"id":"10","name":"Octobre"},{"id":"11","name":"Novembre"},{"id":"12","name":"Decembre"}]};
$scope.months = $scope.list_months.months;

the output of the months are working perfectly and also gets initialized easily by assining a value to $scope.month, however it's an other story for the years, when I refresh the app sometimes the list appears and other times it doesn't (the dropdown list is empty) .
Since it appears correctly that means that the problem is not in SQL but what makes it disappear ?? Could you please help me find out what I'm doing wrong ?

Thanks in advance


You are setting $scope.years in the event handler for the object. This is triggered from an external source out side of Angular, which means it is unaware of the change and so will not run a $digest() to update the page.

You need to manually call $scope.$apply() after setting the years and year porperties:

socket.on('response', function (data){
    $scope.years =data.rep;
    $scope.year = "2016";

It may occasionally seem to be working because another action on the page is causing Angular to run a $digest(), and the years dropdown gets re-rendered as a side effect of that.