ThinkBonobo ThinkBonobo - 4 months ago 9
AngularJS Question

not setting the ng-options select to the predefined ng-model results

I have a value fed in and want it preselected in the select dropdown. The complication is that the model is an object not a simple string. I tried using track by but it does not seem to solve the issue... Maybe you can help?

Let's assume the models in the javascript when the controller loads:

$scope.condition = {name: 'blah', value: '{"id":2,"value":"Monthly Flyer"}' }
$scope.options = [
{"id":1,"value":"Winter Catalog"},
{"id":2,"value":"Monthly Flyer"},
{"id":3,"value":"Sample Catalog"},
{"id":4,"value":"Senior Living"},
...]


Notice how the second one is the same looking object as the first... however, technically it would have a different object reference so

angular.toJson($scope.condition) === angular.toJson(options[1])
is
true

BUT
$scope.condition === options[1]
is
false


Here's the code

<select class="form-control" ng-model="condition.value"
ng-options="opt as (opt.value + ' [' + opt.id + ']')
for opt in options.picklistOptions track by opt.id"></select>


Why do you think it's not loading?

Answer

Well, I'm not sure what you're trying to do, but I think you have an object saved somewhere and you want to select the <option> based on this.

Then, if I'm correct you just made ​​the mistake of having placed the ng-model as condition.value instead of just condition.

See it working:

(function() {
  "use strict";
  angular.module('app', [])
    .controller('mainCtrl', function($scope) {
      $scope.options = {};
      $scope.options.picklistOptions = [  
         {  
            "id":1,
            "value":"Winter Catalog"
         },
         {  
            "id":2,
            "value":"Monthly Flyer"
         },
         {  
            "id":3,
            "value":"Sample Catalog"
         },
         {  
            "id":4,
            "value":"Senior Living"
         }
      ];

      $scope.condition = {
        "id":2,
        "value":"Monthly Flyer"
      };         
    });
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <select class="form-control" ng-model="condition" ng-options="opt as (opt.value + ' [' + opt.id + ']') for opt in options.picklistOptions track by opt.id"></select>
  <hr>
  <span ng-bind="condition | json"></span>
</body>

</html>

Comments