0

I have an issue when I am trying to use ng-options and ng-switch together in AngularJS to dynamically change what content is put on the page for a widget builder I am working on.

I have two issues I am experiencing:
1. I can't seem to set ng-option to default to the value being set by the model from the json it displays.
2. When I change the ng-option field the switch below breaks and no longer showes the correct code.

Here is the code:

<div ng-app="">
  <div data-ng-controller="SimpleController">
    Type: <select ng-model="config.type" ng-options="inputTypes.option for inputTypes in dropDownOptions"></select><br/>
    Source/Content: <input type="text" ng-model="config.content" /><br/>
    <br/>
    <div ng-switch on="config.type">
      <img ng-switch-when="image" ng-src="{{config.content}}">
      <div ng-switch-when="text" >{{config.content}}</div>
    </div>
  </div>
</div>
<script>
  function SimpleController($scope) {
    $scope.dropDownOptions = [
  {"option": "image"},
  {"option": "text"}
 ];
 $scope.config = {
   "type":"text",
   "content":"Hello"
 };
  }
</script>

and here is a link to jsFiddle to run it: http://jsfiddle.net/jpeak/dkvwa/

MrCrowly
  • 168
  • 2
  • 13

1 Answers1

1

The issue is that when you use ng-option and select an item, it selects the whole object, even though just the single key that you specify appears in the selects. So when you select "text", $scope.config.type was being set to {'option':'text'} instead of just "text".

Sharondio
  • 2,605
  • 13
  • 16
  • That makes sense but how would you fix this so that it sets correctly? Any idea on the issue one as well? Thanks for the help. – MrCrowly Jul 19 '13 at 22:20
  • It worked for me when I changed the $scope.dropDownOptions to be a simple list instead of objects: http://jsfiddle.net/wKzZA/3/ – Sharondio Jul 19 '13 at 22:31
  • Even better answer is from [this question](http://stackoverflow.com/questions/15525685/angularjs-how-to-get-the-key-of-a-json-object) that shows how to split the key value pair – MrCrowly Jul 21 '13 at 19:59
  • That question refers to ng-repeat and it's a nifty trick, but it doesn't address the problem you were having about the select with ng-options selecting the entire object instead of just the value. If you wanted/needed to retain the whole object for the ng-options, you could also have put "config.type.option" on your ng-switch like this: http://plnkr.co/edit/hiNmpc?p=preview – Sharondio Jul 22 '13 at 13:33