i'm new angularjs , struggling should easy.
users add new beers on screen , beer may have more 1 style - 'add' button creates new 'style' combo box , 'remove' on left side, well, removes it.
problem when user selects 1 style list doesn't appear selected in combo box - ie, style field empty after dropdown list has been collapsed/closed again.
so here code:
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 style.name 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 }; }
the styleid correctly set in array, problem in screen.
have spotted wrong in code?
p.s.: suspect fact have 2 controllers - beercontroller , 'nested' stylecontroller in same view may related root cause.
as mentioned i'm brand new angularjs mistake rather simple. instead of using on-change, i've binded selected value backing object directly:
<select class="form-control" ng-controller="stylectrl" ng-model="beer.styles[$index].id" ng-options="style.id style.name style in styles">
that got job done. silly oversight.
Comments
Post a Comment