naveen naveen - 25 days ago 9
Javascript Question

How to get dropdown value in angular?

I have a list, in which each item there is a dropdown .Initial or selected value of each dropdown is

A
.Thre is button also present.When I changed the dropdown value it should change the button text.Which is currently working.

Issue is when each dropdown selected value is
A
then only it show 'Fixed' button text otherwise
NOT Fixed


https://plnkr.co/edit/8qxZRhNOryGl2f9NFEz5?p=preview

steps to reproduce issue.


  1. Currently all dropdown show
    A
    and button text is
    Fixed
    .

  2. now change first drodown value
    A
    to
    B
    , now button text is
    Not Fixed
    .

  3. Again change second drodown value
    A
    to
    B
    , now button text reamin same.

  4. If you again change the value of first dropdown
    B
    to
    A
    .it show button text is
    Fixed
    why ?? it should show button text value
    NOT Fixed'.
    Fixed
    text only show when each dropdown value is
    A`.

    $scope.change = function(value){
    console.log(value);
    if(value !='A'){
    $scope.btn = ' NOT Fixed';
    }else{
    $scope.btn = 'Fixed';
    }

    }


Answer Source

Assuming the following rule: when all dropdown values is A, then the text of the button must be "Fixed", otherwise it is "Not Fixed".

You are not checking properly for the condition. Your piece of code will set the button text to 'Fixed' if at any moment the value of the last selected dropdown is not "A". It does not take in account all the other dropdown's values. This is a way to achieve want you want to:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.btn = 'Fixed';
  $scope.arr = [1, 2, 3];
  $scope.selectedValues = {
    [1]: 'A',
    [2]: 'A',
    [3]: 'A'
  };

  $scope.change = function() {
    if (
      Object
        .values($scope.selectedValues)
        .every(function(e) { return e === 'A'; })
    ) {
      $scope.btn = 'Fixed';
    } else {
      $scope.btn = 'NOT Fixed';
    }
  }

  $scope.change();
});
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <button>{{btn}}</button>
  <div ng-repeat="x in arr">{{x}}
    <select class="selectpicker" ng-model="selectedValues[x]" ng-change="change(selectedValue)">
                <option>A</option>
                <option>B</option>
                <option>C</option>
          </select>

  </div>
</body>

</html>