0

I am new to ionic + angularJS... I have created a select item drop down like this

<div class="list">
    <div class="item item-input item-select">
      <div class="input-label" >
       Unit
     </div>
      <select id="unit">
        <option selected>Kilometer</option>
        <option>Mile</option>
      </select>
 </div>
</div>

I am wanting to get the value with angularJS... I have tried this.. The scope.convert is coming when I click a button.

$scope.convert = function() {

alert($scope.unit);
};

It outputs "undefined".. Why is this?

1 Answer 1

1

$scope.unit is actually not defined in the scope, hence you get undefined. You have to define unit on the scope. Since this is an angular application, you can do it the angular way.

In your controller, you want to define a model to hold the value selected. Lets call this model unit like you are actually trying to do. Hence you can initialize this model to Kilometer in your controller.

$scope.unit = 'Kilometer'

Now you need an array of options. This can be set up in your controller as well.

$scope.unitOptions = ['Kilometer', 'Mile']

We use scope to expose our models to the view, hence in your view, you can access this models as follow:

<select id='unit' ng-options="unit for unit in unitOptions">

You will get a dropdown with 'Kilometer' and 'Mile'. You can select any one of them and your model unit will be updated.

//This should now work
$scope.convert = function() { 
    alert($scope.unit);
 };

Note: I left the id attribute on the select element to show it has nothing to do with the model in your controller.

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

2 Comments

Thank you so much! AngularJS is very foreign to me.
You welcome. AngularJS is fun. Enjoy the experience.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.