2017-07-03 99 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();' 。 –