Program Tip

선택 상자의 각도, 부울 값

programtip 2020. 11. 19. 21:57
반응형

선택 상자의 각도, 부울 값


여기에서 선택을 사용하여 부울 값을 true 또는 false로 설정하고 싶습니다.

<select class="span9" ng-model="proposal.formalStoryboard">
<option value="false">Not Included</option>
<option value="true">Included</option>
</select>

값 (proposal.formalStoryboard)이 true 또는 false로 올바르게 설정 되었지만 값이 이미 할당 된 경우 변경 사항이 선택 상자에 반영되지 않습니다.

값 대신 ng-value = "true"및 ng-value = "false"를 시도했지만 제대로 작동하지 않습니다.


편집 : 논평자들은 내 원래 솔루션이 주장대로 작동하지 않았다고 지적했습니다. 아래 다른 사람의 정답을 반영하도록 답변을 업데이트했습니다 (허용 된 답변은 삭제할 수 없습니다).

Angular 1.0.6의 경우 다음 HTML을 고려하십시오.

<div ng-app="">
  <div ng-controller="MyCntrl">
    <select ng-model="mybool"
            ng-options="o.v as o.n for o in [{ n: 'Not included', v: false }, { n: 'Included', v: true }]">
    </select>
    <p>
        Currently selected: <b>{{ mybool }}</b> opposite: {{ !mybool }}
   </p> 
 </div>
</div>

그리고이 자바 스크립트 :

function MyCntrl($scope) {
    $scope.mybool = true;
}

여기에 작업입니다 DEMO 각도 1.0.6 및 여기에 작업입니다 DEMO 약간 다른 각도 1.3.14에 대해.


다음과 같이하십시오.

<select ng-model="someModel" ng-options="boolToStr(item) for item in [true, false]">
</select>

정의 :

$scope.boolToStr = function(arg) {return arg ? 'Included' : 'Not included'};

왜 이것을 사용하지 않습니까?

<select class="form-control" ng-options="(item?'Included':'Not Included') for item in [true, false]"></select>

어떤 버전의 angular가 지원되는지 잘 모르겠지만 이제 ng-value옵션 요소에서를 사용할 수 있습니다 . 귀하의 HTML은 다음과 같이 작동합니다.

<select ng-model="proposal.formalStoryboard">
    <option ng-value="true">Included</option>
    <option ng-value="false">Not Included</option>
</select>

라디오 및 확인란에서도 작동합니다.


이에 대한 지침을 사용하는 것이 좋습니다. 평소와 같이 더 권위 있고 직접적인 제어를 선호하여 시간 초과 및 기타 비동기 작업을 피하려고합니다.

directives.directive('boolean', function() {
  return {
    priority: '50',
    require: 'ngModel',
    link: function(_, __, ___, ngModel) {
      ngModel.$parsers.push(function(value) {
        return value == 'true' || value == true;
      });

      ngModel.$formatters.push(function(value) {
        return value && value != 'false' ? 'true' : 'false';
      });
    }
  };
});

우선 순위는 다른 지시문보다 먼저 수행되도록 특별히 설정됩니다 (일반적으로 우선 순위가 설정되어 있지 않으며 기본값은 0).

예를 들어, 부트 스트랩 플러그인 에서 요소 selectpicker를 래핑하는 지시문 과 함께이 지시문 (참 / 거짓 선택)을 사용 합니다.selectselectpicker

편집하다:

여기서주의해야 할 점은 html 값이 문자열 값이어야한다는 것입니다. 지시어가하는 일은 뷰와 모델간에 변환하여 모델 값을 유지하고 boolean뷰를 string형식으로 유지하는 것 입니다.

%select.selectpicker{ ng: { model: 'modelForm.listed' }, selectpicker: '{ }', boolean: true }
  %option{ value: 'true' } Listed
  %option{ value: 'false' } Unlisted

나는 당신을 위해 샘플을 만들었습니다 . 이것을 확인 하십시오 .

UI 바인딩을 구동하기 위해 모델을 사용하고 싶습니까?

<div ng-app ng-controller="Ctrl">
    <select class="span9" ng-model="proposal.formalStoryboard">
        <option value="false">Not Included</option>
        <option value="true">Included</option>
    </select>
    <button ng-click="changeValue();">Click</button>
<div>

function Ctrl($scope) {
    $scope.proposal = {};
    $scope.proposal.formalStoryboard = true;

    $scope.changeValue = function () {
        $scope.proposal.formalStoryboard = !$scope.proposal.formalStoryboard;
        console.log($scope.proposal.formalStoryboard);
    }
}

이것도 작동합니다. 값에 대해 각도 표현식을 입력하여 값을 부울로 지정하십시오.

<select class="span9" ng-model="proposal.formalStoryboard">
    <option value="{{false}}" 
           ng-selected="proposal.formalStoryboard === false">
           Not Included
    </option>
    <option value="{{true}}"
            ng-selected="proposal.formalStoryboard === true">
            Included
    </option>
</select>

I had very little success with this frustrating issue. My solution, while not too elegant since it's an additional line of code, solved it every time. This may not work in every application.

$scope.myObject.myBooleanProperty = $scope.myObject.myBooleanProperty.toString();

Turning it into a "real" string before trying to rebind it to the model displayed on the page allowed it to correctly select the value.


Angular does a strict comparsion between the Value bind to ng-model and the Values in the given Options. The Values given in the initial Question are the Strings "false" and "true". If the Value of ng-model is of Type bool and defined like {"Value":false}, Angulars strict === comparsion between string and bool does never match so the select-box is empty.

The real Problem is- if you select a Value, the Type changed from bool to string ({"Value":false} --> {"Value":"false"})can cause errors if posted back.

The best Solution for both issues for me was the one of Thiago Passos in this Post. (https://stackoverflow.com/a/31636437/6319374)


<script type='text/javascript'>
function MyCntrl($scope) {<!--from   ww w . j  a  v a 2s.  c om-->
  $scope.mybool = true;
}

</script>
</head>
<body>
  <div ng-app="">
  <div ng-controller="MyCntrl">
    <select ng-model="mybool">
        <option value="false">Not Included</option>
        <option value="true">Included</option>
    </select>
    <p>
    Currently selected: {{ mybool }}
   </p>
 </div>
</div>
</body>
</html>

참고URL : https://stackoverflow.com/questions/17753927/angular-boolean-value-in-a-select-box

반응형