Проблемы при получении значения ключа от объекта с помощью md-select AngularJs 1.XX

У меня проблема с получением Value из Key из объекта, который выбран с помощью md-select в приложении AngularJs (версия 1.XX).

У меня две выпадающие Department " а также " Designation ". Сначала я загрузил Отдел и, основываясь на выборе Отдела, Назначение будет автоматически заполнено. Пожалуйста, взгляните на объект JSON.

{
   "Status":true,
   "Message":"",
   "Result":[
      {
         "DepartmentId":1,
         "Name":"Bala",
         "Designation":[
            {
               "DesignationId":1,
               "DepartmentId":1,
               "Name":"Software Engg"
            },
            {
               "DesignationId":3,
               "DepartmentId":1,
               "Name":"Sr. Human Resouce"
            },
            {
               "DesignationId":2,
               "DepartmentId":1,
               "Name":"Sr. Software Engg"
            }
         ]
      },
      {
         "DepartmentId":2,
         "Name":"Dev",
         "Designation":[

         ]
      },
      {
         "DepartmentId":3,
         "Name":"HR Team",
         "Designation":[

         ]
      },
      {
         "DepartmentId":4,
         "Name":"Sales",
         "Designation":[
            {
               "DesignationId":4,
               "DepartmentId":4,
               "Name":"Sr. Sales Manager"
            }
         ]
      }
   ]
}

Пожалуйста, посмотрите код

<!DOCTYPE html>
<html>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.1/angular-material.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-animate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-aria.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-messages.min.js"></script>

<!-- Angular Material Library -->
<script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.1/angular-material.min.js"></script>
<body ng-app="myApp">

<div ng-controller="myCtrl">
  <p>Department:</p>
  <md-select ng-model="select.Department" tabindex="9" ng-change="onChange(select.Department)">
    <md-option ng-repeat="key in loadUpData.Department" value="{{key}}">{{key.Name}}</md-option>
  </md-select>
  <p>Department ID:</p>
  <md-input-container class="md-block">
    <input type="text" ng-model="select.Department.DepartmentId" maxlength="300" tabindex="32" />
  </md-input-container>
  <br/>
  <p>Designation:</p>
  <md-select ng-model="select.Designation" tabindex="9">
    <md-option ng-repeat="key in designationData" value="{{key}}">{{key.Name}}</md-option>
  </md-select>
  <p>Designation ID:</p>
  <md-input-container class="md-block">
    <input type="text" ng-model="select.Designation.DesignationId" maxlength="300" tabindex="32" />
  </md-input-container>
</div>

<script>
var app = angular.module('myApp', ['ngMaterial']);

app.controller('myCtrl', function($scope) {
  $scope.loadUpData = {
    Department: angular.fromJson("{" +
      "   \"Status\":true," +
      "   \"Message\":\"\"," +
      "   \"Result\":[" +
      "      {" +
      "         \"DepartmentId\":1," +
      "         \"Name\":\"Bala\"," +
      "         \"Designation\":[" +
      "            {" +
      "               \"DesignationId\":1," +
      "               \"DepartmentId\":1," +
      "               \"Name\":\"Software Engg\"" +
      "            }," +
      "            {" +
      "               \"DesignationId\":3," +
      "               \"DepartmentId\":1," +
      "               \"Name\":\"Sr. Human Resouce\"" +
      "            }," +
      "            {" +
      "               \"DesignationId\":2," +
      "               \"DepartmentId\":1," +
      "               \"Name\":\"Sr. Software Engg\"" +
      "            }" +
      "         ]" +
      "      }," +
      "      {" +
      "         \"DepartmentId\":2," +
      "         \"Name\":\"Dev\"," +
      "         \"Designation\":[" +
      "         ]" +
      "      }," +
      "      {" +
      "         \"DepartmentId\":3," +
      "         \"Name\":\"HR Team\"," +
      "         \"Designation\":[" +
      "         ]" +
      "      }," +
      "      {" +
      "         \"DepartmentId\":4," +
      "         \"Name\":\"Sales\"," +
      "         \"Designation\":[" +
      "            {" +
      "               \"DesignationId\":4," +
      "               \"DepartmentId\":4," +
      "               \"Name\":\"Sr. Sales Manager\"" +
      "            }" +
      "         ]" +
      "      }" +
      "   ]" +
      "}").Result
  };

  $scope.Select = {
    Department: {},
    Designation: {}
  };

  $scope.onChange = function(selected) {
      var Designation = JSON.parse(selected).Designation;
      console.log(Designation);
      $scope.designationData = Designation;
  };

});
</script>
</body>
</html>

Я пытаюсь отобразить DepartmentId а также DesignationId выбранного предмета, но я не могу получить идентификатор. Пожалуйста, помогите мне.

1 ответ

Нужно исправить две основные вещи:

  1. Вы определяете $scope.Select = ... в вашем контроллере, но попробуйте ссылаться на него с ng-model="select.Department" в представлении. JavaScript/Angular чувствителен к регистру, поэтому Select !== select - убедитесь, что ссылаетесь на переменные в одном и том же случае.

  2. На <md-option> использование элементов ng-value="key" вместо value="{{key}}" когда вы хотите привязать значение объекта к элементу управления. С этим исправлено вам не нужно JSON.parse(...) в обработчике onChange.

С этими двумя изменениями вот обновленный код:

    <!DOCTYPE html>
    <html>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.1/angular-material.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-animate.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-aria.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-messages.min.js"></script>
    
    <!-- Angular Material Library -->
    <script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.1/angular-material.min.js"></script>
    <body ng-app="myApp">
    
    <div ng-controller="myCtrl">
      <p>Department:</p>
      <md-select ng-model="select.Department" tabindex="9" ng-change="onChange(select.Department)">
        <md-option ng-repeat="key in loadUpData.Department" ng-value="key">{{key.Name}}</md-option>
      </md-select>
      <p>Department ID:</p>
      <md-input-container class="md-block">
        <input type="text" ng-model="select.Department.DepartmentId" maxlength="300" tabindex="32" />
      </md-input-container>
      <br/>
      <p>Designation:</p>
      <md-select ng-model="select.Designation" tabindex="9">
        <md-option ng-repeat="key in designationData" ng-value="key">{{key.Name}}</md-option>
      </md-select>
      <p>Designation ID:</p>
      <md-input-container class="md-block">
        <input type="text" ng-model="select.Designation.DesignationId" maxlength="300" tabindex="32" />
      </md-input-container>
    </div>
    
    <script>
    var app = angular.module('myApp', ['ngMaterial']);
    
    app.controller('myCtrl', function($scope) {
      $scope.loadUpData = {
        Department: angular.fromJson("{" +
          "   \"Status\":true," +
          "   \"Message\":\"\"," +
          "   \"Result\":[" +
          "      {" +
          "         \"DepartmentId\":1," +
          "         \"Name\":\"Bala\"," +
          "         \"Designation\":[" +
          "            {" +
          "               \"DesignationId\":1," +
          "               \"DepartmentId\":1," +
          "               \"Name\":\"Software Engg\"" +
          "            }," +
          "            {" +
          "               \"DesignationId\":3," +
          "               \"DepartmentId\":1," +
          "               \"Name\":\"Sr. Human Resouce\"" +
          "            }," +
          "            {" +
          "               \"DesignationId\":2," +
          "               \"DepartmentId\":1," +
          "               \"Name\":\"Sr. Software Engg\"" +
          "            }" +
          "         ]" +
          "      }," +
          "      {" +
          "         \"DepartmentId\":2," +
          "         \"Name\":\"Dev\"," +
          "         \"Designation\":[" +
          "         ]" +
          "      }," +
          "      {" +
          "         \"DepartmentId\":3," +
          "         \"Name\":\"HR Team\"," +
          "         \"Designation\":[" +
          "         ]" +
          "      }," +
          "      {" +
          "         \"DepartmentId\":4," +
          "         \"Name\":\"Sales\"," +
          "         \"Designation\":[" +
          "            {" +
          "               \"DesignationId\":4," +
          "               \"DepartmentId\":4," +
          "               \"Name\":\"Sr. Sales Manager\"" +
          "            }" +
          "         ]" +
          "      }" +
          "   ]" +
          "}").Result
      };
    
      $scope.select = {
        Department: {},
        Designation: {}
      };
    
      $scope.onChange = function(selected) {
          var Designation = selected.Designation;
          console.log(Designation);
          $scope.designationData = Designation;
      };
    
    });
    </script>
    </body>
    </html>

Другие вопросы по тегам