0

I am using https://github.com/localytics/angular-chosen to allow for select tags with search capability for many options.

The problem I'm having is with preselecting an option on an already saved vendor object. When creating a new one there is now issue, but if we're viewing an existing vendor, I want to show the vendor's name in the select box, rather than the placeholder.

<select chosen 
        ng-model="myVendor" 
        ng-options="vendor['public-id'] as vendor.name for vendor in vendors" 
        data-placeholder="Nah">
</select>

And in my controller, I'm setting the model by hand $scope.myVendor = "Some value"

The problem is that I'm populating the options with an object, instead of a key/value. I found an example of it working with a key/value, but haven't had success adapting this to objects as options.

I've even tried setting myVendor to the matching object that I want selected, with no luck.

Plunker of issue

Seth
  • 10,198
  • 10
  • 45
  • 68

1 Answers1

1

I updated the plunker and change my previous changes on the plugin. this was not the issue. I don't understand how it was giving me errors there. The solution is to track with an object and two functions the id and the name:

// Controller

 $scope.vendors = [
    {
      "public-id": "1234",
      "name": "stugg"
    },
    {
      "public-id": "4321",
      "name": "pugg"
    }
  ];
  $scope.myVendor = {name: "pugg", id:""};

  $scope.updateMyVendorName = function () {
    var found = false,
    i = 0;
    while (!found && i < $scope.vendors.length)  {
      found = $scope.vendors[i]['public-id'] === $scope.myVendor.id;
      if (found) {
        $scope.myVendor.name = $scope.vendors[i].name;
      }
      i++;
    }
  }

  findVendorByName();

  function findVendorByName () {
        var found = false,
    i = 0;
    while (!found && i < $scope.vendors.length)  {
      found = $scope.vendors[i]['name'] === $scope.myVendor.name;
      if (found) {
        $scope.myVendor.id = $scope.vendors[i]['public-id'];
      }
      i++;
    }
  }

// template

<select chosen class="form-control span6" ng-options="vendor['public-id'] as vendor.name for vendor in vendors" ng-model="myVendor.id" ng-change="updateMyVendorName()">

{{myVendor.name}}
Raulucco
  • 3,406
  • 1
  • 21
  • 27
  • It's working for you? I still see the placeholder an not the `pugg` selected in the plunker that you linked. – Seth Jun 29 '15 at 13:32
  • Yes sorry I got console errors on those lines and i forgot about the actual question. The problem is that you use the name property as the model but the select options are tracket bu the public-id. So you have to iterate the options to find the one that match, i'll update the plunker – Raulucco Jun 29 '15 at 14:01
  • That's the gist. I'm implementing it a little different, but the model structure is exactly what I needed. Thank you very much for your help, @Raulucco – Seth Jun 29 '15 at 16:30