I need some help with AngularJS as I am still getting the hang of it.
Take a look at this not-so-pretty page: https://i.sstatic.net/Dtm7j.png
This page allows users to add new beers, and each beer can have multiple styles. Clicking 'Add' creates a new dropdown for selecting a style, while clicking 'Remove' removes an existing one. The issue is that selected styles do not appear in the dropdown after selection - they remain empty once collapsed or closed.
Here is the code snippet:
Beer View
<div class="form-group" ng-repeat="style in beer.styles">
<label for="style" class="col-sm-1 control-label" ng-if="$index == 0" >Style</label>
<div class="col-sm-1" ng-if="$index > 0">
<button type="button" class="btn btn-danger" ng-click="removeStyle($index)">Remove</button>
</div>
<div class="col-sm-10">
<select class="form-control"
ng-controller="styleCtrl"
ng-model="selectedStyleId"
ng-options="style.id as style.name for style in styles"
ng-change="updateStyle($index, selectedStyleId)">
</select>
</div>
<div class="col-sm-1">
<button type="button" class="btn btn-primary" ng-click="addNewStyle()">Add</button>
</div>
</div>
Style Controller (Dummy Impl)
.controller('styleCtrl', ["$scope", "$location", function ($scope, $location) {
$scope.styles = [
{ 'id': '1',
'name': 'Lager' },
{ 'id': '2',
'name': 'American Blonde Ale' },
{ 'id': '3',
'name': 'American Stout' },
{ 'id': '4',
'name': 'Cream Ale' },
{ 'id': '5',
'name': 'Bock' },
{ 'id': '6',
'name': 'German Pilsener' }
];
}]);
Beer Controller
.controller('beerCtrl', ["$scope", "$location", function ($scope, $location) {
$scope.beer = {
'styles': [
{ 'id' : '-1' }
]
}
$scope.addNewStyle = function() {
$scope.beer.styles.push({ 'id': '-1' });
}
$scope.removeStyle = function(index) {
$scope.beer.styles.splice(index, 1);
}
$scope.updateStyle = function(index, styleId) {
$scope.beer.styles[index] = { 'id': styleId };
}
Although the styleId is correctly recorded in the array, the display on the screen is where the problem lies.
Do you notice any mistakes in my code?
P.S.: I suspect that having two controllers - BeerController and a 'nested' StyleController - in the same view might be causing the issue.