0

I am new to angularjs and still learning the language. I created a select box in an html and I want to populate it with a variable in my controller.

I am able to get the variable in the html using {{variablename}}, but I am not able to get the sub objects within it. Please see my code here.
You can see that it displays "repeatSelect" in the html but if i try to index an object within it, it doesn't show.(getID is always empty)

Controller has a $scope variable as follows

controller('ExampleController', ['$scope', function($scope) {
    $scope.repeatSelect = null;
    $scope.data = {
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ],
    };
 }]);

In the html code,

<tt>repeatSelect = {{repeatSelect}}</tt><br/>
  <tt>getID = {{repeatSelect.id}}</tt><br/>

repeatSelect works fine, but repeatSelect.id doesn't.

Please guide

1 Answer 1

1

Use ng-options built in directive instead https://docs.angularjs.org/api/ng/directive/ngOptions.

It is designed specifically to work with HTML select lists and has plenty of powerful options.

<div ng-controller="ExampleController">
    <label> Repeat select: </label>
    <select ng-options="option as option.name for option in data.availableOptions track by option.id" ng-model="repeatSelect"></select>
  <hr>
  <tt>repeatSelect = {{repeatSelect}}</tt><br/>
  <tt>getID = {{repeatSelect.id}}</tt><br/>
</div>

Please see plunkr here: http://plnkr.co/edit/kIcH5fF7suhN0rhVDez8?p=preview

Sign up to request clarification or add additional context in comments.

5 Comments

ah beat me to it, but you dont really need the "track by"
I know it's a habit now due to issues with performance that I have experienced.
I see, never used track before always "as". Sorry to be slow but what's the difference between "as" and "track by" as they basically do the same?
This does not answer the question; just provides an alternative. Do you have an answer for why the code given is not working?
nCore track by makes it faster because it gives angular a way to determine which element is which without comparing the entire object, only useful when the elements in the array actually change though. Cst1992 the way the list was defined is not designed for select lists the ng-model was being bound to the serialization of the object not the actual object in memory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.