Issue
I have a select
dropdown I'm setting up with an ng-options
. It's showing up fine in the HTML page, but when I select an option, the variable defined by ng-model
is not being updated in $scope
.
HTML:
<select ng-model="selected_ingredient"
ng-options="item as item.ingredient for item in available_ingredients"
ng-change="selectIngredient()">
<option value="">Add an ingredient...</option>
</select>
AngularJS:
$scope.selectIngredient = function() {
if ( $scope.debug > 0 ) {
console.log( "Selected ingredient:" );
console.log( $scope.selected_ingredient );
}
};
Console output (after dropdown item selected, $scope.debug
is 1):
Selected ingredient:
undefined
I would like $scope.selected_ingredient
to be the object item
that is displayed by the dropdown element I select. What am I doing wrong?
Solution
I used a workaround from @billy_comic in the comments
<select ng-model="$parent.selected_ingredient"
ng-options="item as item.name for item in available_ingredients"
ng-change="$emit( 'SelectedIngredient', $parent.selected_ingredient )">
<option value="">Add an ingredient...</option>
</select>
in my HTML as well as the following JS function
$scope.$on( "SelectedIngredient" , function( evt, data ) {
if ( $scope.debug > 0 ) {
console.log( "Selected ingredient:" );
console.log( data );
}
});
that produces the expected values. Thanks so much!
Answered By - Mason Hicks
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.