2017-07-03 98 views
0

我正在使用ng-options来显示带有选项的下拉列表。假设我有三个选项,例如选项1,选项2,选项3.默认选项1被选中,现在如果用户选择选项2,那么$pristine变成False,再次如果他选择选项1,则从angularjs的预期$pristine应该是假的,但根据用户他并没有改变我一直在寻找一种方式option.So检测到这种变化检查下拉列表的状态是否已更改

+0

可以为您发布你尝试过什么? –

回答

0

这里是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; 
    }) 
    }); 

你有你的列表模式则可以做到这一点

+0

这可以在ng-change本身完成,不需要额外的$ watch –

+0

@RohanKawade然后你可以使用方法来设置它默认'$ scope.myForm。$ setPristine(true);'参考https:// docs .angularjs.org/api/ng/type/form.FormController –

0

这正是NG-变化是增加的手表。

用法会是这样(加$指数向您展示另一种选择):

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] 
     }; 
}); 
+0

但仍然是$ pristine条件仍然是错误的。 –

+0

@RohanKawade如果你想把它设置为true,你可以在'$ scope.optionChanged'函数中调用'myform. $ setPristine();' 。 –