FlyingCat
FlyingCat

Reputation: 14290

How to get the selected value in Select element in my case?

I am trying to get the option value when user selects a option in Angular way. I have something like'

<div ng-controller="test">
  <select ng-model="selectedProduct" ng-options="product.name for product in products">
     <option value="">Please select a product</option>
  </select>
</div>

In my js

app.controller('test', function ($scope, $http, $modal) {

    console($scope.selectedProduct)   -> undefined. 

})

I want to get the selected value when user makes a selection. Can anyone help me about it? thanks a lot!

Upvotes: 0

Views: 46

Answers (3)

user2882597
user2882597

Reputation: 424

Here is an example of this working. You should define a default value within your controller's $scope to ensure the value is defined. From there it is easy to access the model via {{ myproduct }} or $scope.myproduct depending on where it is being accessed.

Upvotes: 1

gkalpak
gkalpak

Reputation: 48211

You can use ngChange to fire an event whenever the value changes in the view:

<select ng-model="selectedProduct" ng-options="product.name for product in products"
        ng-change="doSomething(selectedProduct)">
    <option value="">Please select a product</option>
</select>

app.controller('test', function ($scope, $http, $modal) {
    ...
    $scope.doSomething = function (product) {
        // Do stuff with product
    };

See, also, this short demo.

Upvotes: 1

Mohamed El Mahallawy
Mohamed El Mahallawy

Reputation: 13872

Try this:

<select ng-model="selectProduct" ng-options="option.id as option.name for option in options" ></select>

Secondly, where is your products in your controller?

Upvotes: 1

Related Questions