IT박스

각도 JS를 사용하여 드롭 다운 목록 컨트롤의 선택된 옵션을 설정하는 방법

itboxs 2020. 6. 24. 07:49
반응형

각도 JS를 사용하여 드롭 다운 목록 컨트롤의 선택된 옵션을 설정하는 방법


Angular JS를 사용하고 있으며 각도 JS를 사용하여 드롭 다운 목록 컨트롤의 선택된 옵션을 설정해야합니다. 이것이 터무니없는 경우 용서하지만 Angular JS를 처음 사용합니다.

내 HTML의 드롭 다운 목록 컨트롤은 다음과 같습니다.

 <select ng-required="item.id==8 && item.quantity > 0" name="posterVariants"
   ng-show="item.id==8" ng-model="item.selectedVariant" 
   ng-change="calculateServicesSubTotal(item)"
   ng-options="v.name for v in variants | filter:{type:2}">
  </select>

그것이 채워지면 나는 얻는다.

 <select ng-options="v.name for v in variants | filter:{type:2}" ng-change="calculateServicesSubTotal(item)"
ng-model="item.selectedVariant" ng-show="item.id==8" name="posterVariants"
ng-required="item.id==8 &amp;&amp; item.quantity &gt; 0" class="ng-pristine ng-valid ng-valid-required">
    <option value="?" selected="selected"></option>
    <option value="0">set of 6 traits</option>
    <option value="1">5 complete sets</option>
</select>

컨트롤을 value="0"선택 하려면 어떻게 설정 합니까?


귀하의 질문을 이해하기를 희망하지만 ng-model지시문은 컨트롤에서 선택한 항목과의 값 사이에 양방향 바인딩을 만듭니다 item.selectedVariant. item.selectedVariant, JavaScript에서 변경하거나 컨트롤의 값을 변경하면 다른 것이 업데이트됩니다. 경우 item.selectedVariant의 값을 가지며 0, 해당 항목을 선택을하셔야합니다.

variants객체 배열 인 경우 item.selectedVariant해당 객체 중 하나로 설정해야합니다. 귀하의 범위에 어떤 정보가 있는지는 모르지만 여기에 예가 있습니다.

JS :

$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];

HTML :

<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>

그러면 "b"항목이 선택된 상태로 남게됩니다.


이것이 도움이되는지 아닌지는 모르겠지만 같은 문제에 직면했을 때 솔루션을 얻는 방법을 공유하려고 생각했습니다.

속성 별 추적을 사용할 수 있습니다 ng-options.

당신이 가지고 있다고 가정 :

variants:[{'id':0, name:'set of 6 traits'}, {'id':1, name:'5 complete sets'}]

당신은 다음 ng-options과 같이 언급 할 수 있습니다 :

ng-options="v.name for v in variants track by v.id"

이것이 미래에 누군가를 돕기를 바랍니다.


값 0을 할당하면 item.selectedVariant자동으로 선택되어야합니다. http://docs.angularjs.org/api/ng.directive:select 에서 샘플을 확인하면 기본적으로 단순히 빨간색을 지정하여 빨간색을 선택합니다 $scope.color='red'.


나는 여기에 이미 좋은 답변을 썼지 만 언젠가는 다른 형태로 똑같이 쓰는 것이 도움이 될 수 있습니다.

<div ng-app ng-controller="MyCtrl">
  <select ng-model="referral.organization" ng-options="c for c in organizations"></select>
</div>

<script type='text/javascript'>
  function MyCtrl($scope) {
    $scope.organizations = ['a', 'b', 'c', 'd', 'e'];
    $scope.referral = {
      organization: $scope.organizations[2]
    };
  }
</script>

간단한 방법

응답으로 사용자 또는 정의한 배열 / JSON이있는 경우 먼저 컨트롤러에서 선택한 값을 설정해야하며 동일한 모델 이름을 html에 입력해야합니다. 이 예제는 가장 쉬운 방법으로 설명했습니다. 컨트롤러 내부의
간단한 예
:

$scope.Users = ["Suresh","Mahesh","Ramesh"]; 
$scope.selectedUser = $scope.Users[0];

HTML

<select data-ng-options="usr for usr in Users" data-ng-model="selectedUser">
</select>


내부 컨트롤러의 복잡한 예 :

$scope.JSON = {
       "ResponseObject":
           [{
               "Name": "Suresh",
               "userID": 1
           },
           {
               "Name": "Mahesh",
               "userID": 2
           }]
   };
   $scope.selectedUser = $scope.JSON.ResponseObject[0];

HTML

<select data-ng-options="usr.Name for usr in JSON.ResponseObject" data-ng-model="selectedUser"></select>
<h3>You selected: {{selectedUser.Name}}</h3>    

유용 할 수 있습니다. 바인딩 용량이 항상 작동하는 것은 아닙니다.

<select id="product" class="form-control" name="product" required
        ng-model="issue.productId"
        ng-change="getProductVersions()"
        ng-options="p.id as p.shortName for p in products">
</select>

For example. You fill options list source model from rest-service. Selected value was known befor filling list and was set. After executing rest-request with $http list option be done. But selected option is not set. By unknown reasons AngularJS in shadow $digest executing not bind selected as it shuold be. I gotta use JQuery to set selected. It`s important! Angular in shadow add prefix to value of attr "value" for generated by ng-repeat optinos. For int it is "number:".

$scope.issue.productId = productId;
function activate() {
   $http.get('/product/list')
     .then(function (response) {
       $scope.products = response.data;

       if (productId) {
           console.log("" + $("#product option").length);//for clarity                       
           $timeout(function () {
               console.log("" + $("#product option").length);//for clarity
               $('#product').val('number:'+productId);
               //$scope.issue.productId = productId;//not work at all
           }, 200);
       }
   });
}

Try the following:

JS file

this.options = { 
        languages: [{language: 'English', lg:'en'}, {language:'German', lg:'de'}]
};
console.log(signinDetails.language);

HTML file

<div class="form-group col-sm-6">
    <label>Preferred language</label>
    <select class="form-control" name="right" ng-model="signinDetails.language" ng-init="signinDetails.language = options.languages[0]" ng-options="l as l.language for l in options.languages"><option></option>
    </select>
</div>

This is the code what I used for the set selected value

countryList: any = [{ "value": "AF", "group": "A", "text": "Afghanistan"}, { "value": "AL", "group": "A", "text": "Albania"}, { "value": "DZ", "group": "A", "text": "Algeria"}, { "value": "AD", "group": "A", "text": "Andorra"}, { "value": "AO", "group": "A", "text": "Angola"}, { "value": "AR", "group": "A", "text": "Argentina"}, { "value": "AM", "group": "A", "text": "Armenia"}, { "value": "AW", "group": "A", "text": "Aruba"}, { "value": "AU", "group": "A", "text": "Australia"}, { "value": "AT", "group": "A", "text": "Austria"}, { "value": "AZ", "group": "A", "text": "Azerbaijan"}];
 
 
 for (var j = 0; j < countryList.length; j++) {
      //debugger
      if (countryList[j].text == "Australia") {
          console.log(countryList[j].text); 
          countryList[j].isSelected = 'selected';
      }
      }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<label>Country</label>
<select class="custom-select col-12" id="Country" name="Country"   >
<option value="0" selected>Choose...</option>
<option *ngFor="let country of countryList" value="{{country.text}}" selected="{{country.isSelected}}"   > {{country.text}}</option>
</select>

try this on an angular framework


JS:

$scope.options = [
  {
    name: "a", 
    id: 1 
  },
  {
    name: "b",
    id: 2 
  }
];
$scope.selectedOption = $scope.options[1];

참고URL : https://stackoverflow.com/questions/17968760/how-to-set-a-selected-option-of-a-dropdown-list-control-using-angular-js

반응형