I'm experiencing a strange behaviour, but I don't know who's fault it is.
I have three variables in $scope
that can be changed by the user. They are bind to a select
object through ng-model
.
<select ng-options="hour.label for hour in hours track by hour.val" ng-model="new_hour"></select> HH :
<select ng-options="minute.label for minute in minutes track by minute.val" ng-model="new_minute"></select> MM :
<br />
new_hour = {{ new_hour }}<br />
new_minute = {{ new_minute }} </br>
where the variables are initialized as follows:
$scope.minutes = [];
for(var i = 0; i < 60; ++i)
{
var min = String(i);
if(i < 10)
min = "0" + min;
$scope.minutes.push({ val: i, label: min});
}
$scope.hours = $scope.minutes.slice(0, 24);
$scope.new_minute = $scope.minutes[0];
$scope.new_hour = $scope.hours[0];
Whenever I choose a different time, the values of $scope.new_hour
and $scope.new_minute
change immediately as expected.
However, I have also a button that has a ngClick
and calls some function in the $scope
.
<button ng-click="add_value()">Add value</button>
If I select a new (minute) value and then click on the button, then the $scope
function sees the old values and not the new ones:
$scope.add_value = function()
{
console.log("new_minute: " + $scope.new_minute.val);
}
Let's say I've chosen 03 and then click on the button. The console shows new_minute: 0.
However, if I modify my code:
<button ng-click="add_value(new_minute.val)">Add vaue</button>
and
$scope.add_value = function(new_minute)
{
console.log("new_minute: " + new_minute);
}
Then the value passed to add_value
is always correct. I if open the inspect console and inspect the value of $scope.new_minute.val
, then $scope.new_minute.val
differs from the local variable new_minute
.
I've prepared a fiddle with the basic structure of my code: https://jsfiddle.net/shaoran/tnvou6ud/1/
There everything works as expected, I honestly cannot reproduce this behaviour. Has anybody any idea what might be going on?