I have an old system which needs a bit of a tweak. All works as I expect when I have some AngularJS declarations and plain HTML/JavaScript. Current code is:
<div ng-controller="myController as vm"> <select name="items" id="items"> </select> <script type="text/javascript"> // Sample data const options = [ { value: '1', text: 'Option 1' }, { value: '2', text: 'Option 2' }, { value: '3', text: 'Option 3' }, ]; // Get the select element const select = document.getElementById('items'); // Populate the select with options options.forEach(option => { const opt = document.createElement('option'); // Create a new <option> element opt.value = option.value; // Set the value attribute opt.textContent = option.text; // Set the visible text select.appendChild(opt); // Add the option to the <select> }); </script> </div>
I have some data in myController
declared in the first div ng-controller
which returns an array of data.
Instead of having the items hardcoded as they currently are, how can I use my vm
variable to call getData
(which I already have and is bringing back data) so the items are replaced by the data retrieved by the AngularJS controller?
I tried
const options = vm.getData();
but that didn't work.
I have tried other sites for syntax reference but either way I can't connect it using the JavaScript declaration above
<script>
with AngularJS, which won't work the way you expect. Inside your<script>
,vm
doesn't exist in the global scope. It's part of AngularJS’s internal scope. Soconst options = vm.getData();
won't findvm
there. You should bind the data using Angular templatesng-options
orng-repeat
and not plain JavaScript.