【问题标题】:Check if state of dropdown has changed检查下拉菜单的状态是否已更改
【发布时间】:2017-07-03 07:51:18
【问题描述】:

我正在使用ng-options 显示带有选项的下拉菜单。假设我在其中有三个选项,例如选项 1、选项 2、选项 3。默认情况下选择选项 1,现在如果用户选择选项 2,则 $pristine 变为 @ 987654323@,如果他再次选择选项 1,那么来自 angularjs 的预期 $pristine 应该是假的,但根据用户他没有改变选项。所以我正在寻找一种方法来检测这种变化

【问题讨论】:

  • 您可以发布您尝试过的内容吗?

标签: angularjs select


【解决方案1】:

这里是Js fiddle demo

HTML

<div ng-app="myApp">

  <div ng-controller="ctrl">
    <form name="myForm">
      {{myForm.$pristine}}
      <select ng-model='list' ng-options='item.name for item in data'>
      </select>
    </form>
  </div>
</div>

JS 代码

  var app = angular.module('myApp', []);

  app.controller('ctrl', function($scope) {
    $scope.data = [{
      id: 1,
      name: 'test'
    }, {
      id: 2,
      name: 'test1'
    }];
    $scope.list = $scope.data[0];
    $scope.$watch('list', function(o, n) {
      if ($scope.list == $scope.data[0])
        $scope.myForm.$pristine = true;
    })
  });

你已经在你的列表模型上添加了手表,那么这可以实现

【讨论】:

【解决方案2】:

这正是 ng-change 的用途。

用法是这样的(添加 $index 以显示另一个选项):

HTML

<div ng-app="myApp">
    <div ng-controller="listController">
        <form name="myForm">
            <select ng-model="currOption"
                    ng-options='item.name for item in data'
                    ng-change="optionChanged(currOption, $index)">
            </select>
        </form>
    </div>
</div>

控制器

angular.module('myApp')
    .controller('listController', function($scope) {
         $scope.data = [{
             id: 1,
             name: 'option1'
         }, {
             id: 2,
             name: 'option2'
         }, {
             id: 3,
             name: 'option3'
         }];

        $scope.optionChanged(option, index) {
            // option = the selection the user just made.
            // index = the index of the selection in your data. I.E. $scope.data[index]
        };
});

【讨论】:

  • 但 $pristine 条件仍然为假。
  • @RohanKawade 如果你想将它设置为true,你可以在$scope.optionChanged函数中调用myform.$setPristine();
猜你喜欢
  • 2015-10-12
  • 2020-02-20
  • 2015-08-30
  • 2020-08-11
  • 2017-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-13
相关资源
最近更新 更多