【问题标题】:"checked" and "selected" in HTML for input do not work with AngularJS用于输入的 HTML 中的“选中”和“选择”不适用于 AngularJS
【发布时间】:2015-05-04 01:38:12
【问题描述】:

我正在学习 AngularJS 和用户输入。在我的代码中,我尝试使用“选中”和“选中”设置下拉菜单和单选按钮的默认状态。

但是,它们不能与“ng-model”属性一起使用。

另外,对于第一个单选按钮(升序),空值属性似乎阻碍了“checked”属性。

谁能解释为什么会发生这种情况以及如何绕过这个问题?

<div class="search">
<h1>Artist Directory</h1>

  <label> Search: </label>
      <input ng-model="query" placeholder="Search for artists" autofocus> 
  <label class="formgroup">by: 
      <select ng-model="listOrder" name="direction">
          <option  value ="name" selected="selected"> Name</option>
          <option value="reknown"> Reknown</option>
      </select>
  </label>

  <label class="formgroup">
         <input ng-model="direction" type="radio" value=" " checked>   Ascending
   </label>

  <label class="formgroup">
        <input ng-model="direction" type="radio" value="reverse"> Descending
  </label>

</div>

【问题讨论】:

  • 请提供小提琴。这将帮助我们帮助您:)

标签: html angularjs input option radio


【解决方案1】:

AngularJS 中的 Select 看起来像这样:

<select ng-model="selectedOpt"
      ng-options="opt for opt in listOrder">
</select>

然后回到你设置的控制器

$scope.selectedOpt = $scope.listOrder[0];

您希望默认选择哪个选项。

【讨论】:

    【解决方案2】:

    系上您的按钮并选择一个 ng-model。默认值是您在首次创建范围时放入模型中的值。然后在用户点击时更新值:

    function test($scope) {
      $scope.selected = ['1','3'];
      $scope.checked = "green";
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
    
    <div ng-app>
      <h2>Todo</h2>
      <div ng-controller="test">
                <select name="" ng-model="selected" multiple>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
            </select>
          <br><br>
          <input type="radio" ng-model="checked" value="red">  Red <br/>    
          <input type="radio" ng-model="checked" value="green"> Green <br/>
          <input type="radio" ng-model="checked" value="blue"> Blue <br/>
             
             
            <br>
            Selected : {{selected}}
            <br>
            Checked : {{checked}}
      </div>
    </div>

    查看实际操作:http://jsfiddle.net/913n30zf/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 2013-04-19
      • 2013-10-03
      • 1970-01-01
      • 1970-01-01
      • 2019-07-17
      • 2016-01-17
      相关资源
      最近更新 更多