Reputation: 11
I'm pretty new to Angular. One of the impressions that I'm getting while reading through the documentation is that you should avoid directly accessing the DOM because Angular should be doing this for you. In other words, I should avoid using jQuery to do things.
I'm trying to figure out how to load the values in a select box into Angular's scope variable. For example, if my HTML template includes the following snippet:
<select>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
I'd like to be able to have a variable set in the controller that would look like this after the page is loaded:
$scope.selectvals = [ { value: "1", description: "Option 1" },
{ value: "2", description: "Option 2" },
{ value: "3", description: "Option 3" }
]
I could use JQuery to do this, but then I would be touching the DOM. I was wondering if Angular provides some sort alternative for accomplishing this.
I also know that I could send this info via an Ajax call and use ng-option to load the select, but I would like to save the overhead of an additional Ajax request to load this little information into the select box.
Upvotes: 1
Views: 742
Reputation: 13399
<select ng-model="myVal" ng-options="val.description for val in selectvals"></select>
You bind to the scoped proerty selectvals
that you created and the syntax is as above. Here's the official page for Select
Upvotes: 0
Reputation: 64883
You can use ng-options to populate the list like such:
<div ng-app ng-init="options=[{ value: '1', description: 'Option 1' }, { value: '2', description: 'Option 2'}]">
<select ng-model="selectedOption" ng-options="o.description for o in options"></select>
</div>
You will need to set ng-model to capture the selected item.
Upvotes: 1