Reputation: 21814
The following code from my view works just as expected. player_id is updated whenever I make a new selection:
<div class="form-group">
<select class="form-control" ng-model="player_id" ng-change="hithere();">
<option ng-repeat="player in players" value="{{ player.id }}">{{ player.name }}</option>
</select>
</div>
test works: {{ player_id }}
Bot the code below does not work as I expect. I would expect the log to always print the same value as I see in my view. But instead it prints the default value 0, regardless of my selection in the view.
$scope.player_id = 0;
...
$scope.hithere = function($event){
console.log('Test does not work, prints 0');
console.log($scope.player_id);
};
What is wrong?
Upvotes: 1
Views: 55
Reputation: 536
This scenario is best candidate to use ControllerAs
syntax.
In HTML use ng-controller="NameOfController as vm"
then HTML would be as follows, and you need not require to wrap your model inside extra object.
<div class="form-group">
<select class="form-control" ng-model="vm.player_id" ng-change="hithere();">
<option ng-repeat="player in vm.players" value="{{ player.id }}">{{ player.name }}</option>
</select>
</div>
Upvotes: 1
Reputation: 57874
It's probably a scoping issue. The $scope
in the controller is a parent (or other ancestor) of the scope in the HTML.
Use this instead:
$scope.data = {
player_id: 0
}
And then use data.player_id
everywhere instead of just player_id
.
See Understanding Scopes for more information.
Upvotes: 2