Привязать другое свойство, чем показано в компоненте HTML - PullRequest
0 голосов
/ 17 мая 2018

Считайте, что у меня есть список объектов вроде -

var configs = [{
    id: "1",
    name: "config1"
},
 {
    id: "2",
    name: "config2"
 }
];

Я использую следующее для поиска в списке конфигурации и привязки выбранной конфигурации к другой переменной с именем changed_config.

<table style="width:900px;">
<tr>
   <th style="width:500px; margin:50px">Config Name</th>
   <th style="width:150px;">Config Value</th>
</tr>
<tr ng-repeat="changed_config in changed_configs">
   <td>
      <input type="text" class="form-control" ng-model="changed_config.id" list="names">
      <datalist id="names">
         <option ng-repeat="option in configs | filter:search | limitTo:30" ng-value="option.name"> {{option.name}}
         </option>
      </datalist>
   <td>
      <input type="text" class="form-control" ng-model="changed_config.value">
   </td> 
  </tr>
</table>
<div class="row">
  <button type="button" id="add-reward-grp-btn" ng-click="addConfig()"
       class="btn btn-primary">Add Config                 
  </button>
</div>

Код контроллера (не полный код, только соответствующие фрагменты):

var app = angular.module("drs_scheduler_app", []);
app.controller("CreateSchedulerJob", function ($scope, $http) {
          $scope.changed_configs = []; 
          $scope.configs = [{
                   id: "1",
                   name: "config1"
                   },
                   {
                   id: "2",
                   name: "config2"
                   }
          ];

        $scope.addConfig = function () {
          var config = {
              "id": "",
              "value": ""
          };
          $scope.changed_configs.push(config);
          console.log(config);
          console.log(JSON.stringify($scope.changed_configs));
        }
}

В настоящее время код отображает и связывает name выбранной конфигурации с переменной changed_config. Но мне нужно, чтобы id был привязан к переменной changed_config и name отображался в html.

Если я изменю <option> на использование идентификатора, то будет отображаться id.

Как связать одно свойство с переменной, но показать другое в html ??

1 Ответ

0 голосов
/ 17 мая 2018

Вот решение, которое вам нужно,

Процедура:

  1. Когда option равен selected из datalist Я проверяю , что изменить
  2. что изменение наблюдается через input, к которому добавляется datalist
  3. На этом input change i, e при выборе опции Я назначаю это идентификатор для идентификатора ключа соответствующего changed_config
  4. То есть inturn отображается во втором текстовом поле
  5. Работает на dynamic

// Code goes here

function cntryController($scope) {
  
  
  $scope.LoadSessionData=function(val)
  {
    
     console.log(val);
    
   
    
  };
  
      $scope.changed_configs = []; 
          $scope.configs = [{
                   id: "1",
                   name: "config1"
                   },
                   {
                   id: "2",
                   name: "config2"
                   }
          ];

        $scope.addConfig = function () {
          var config = {
              "id": "",
              "value": ""
          };
          $scope.changed_configs.push(config);
          console.log(config);
          console.log(JSON.stringify($scope.changed_configs));
        }
  
    
  $scope.test = function(data, index){
    console.log(data)
    var newArray = $scope.configs.filter(function (config) {
  return config.name == data;
});
    console.log(newArray)
    if(newArray.length){
      var new_changed_config = $scope.changed_configs[index];
      new_changed_config.id = newArray[0].id;
    }
  }
  
  
  
  
  
}
<!DOCTYPE html>
<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>


<div ng-app="" ng-controller="cntryController">


    <table cellspacing="10" cellpadding="10">
        <tr>
            <th>Config Name</th>
            <th>Config Value</th>
        </tr>
        <tr ng-repeat="changed_config in changed_configs">
            <td>
                <input type="text" class="form-control" ng-model="changed_config.name" list="names" ng-change="test(changed_config.name, $index)">                
                <datalist id="names">
                    <option ng-repeat="option in configs | filter:search | limitTo:30" value={{option.name}}>{{option.name}}
                    </option>
                </datalist>
            </td>
            <td>
                <input type="text" class="form-control" ng-model="changed_config.id"/>
            </td>
        
        </tr>
        

    </table>
    <div class="row">
            <button type="button" id="add-reward-grp-btn" ng-click="addConfig()" class="btn btn-primary">Add Config</button>
        </div>

</div>

</html>

Пожалуйста, запустите приведенный выше фрагмент

Вот рабочая ДЕМО

...