簡體   English   中英

ng-change在選擇框中檢測ng-model是否為null或無效,然后選擇第一個有效選項

[英]ng-change detect if ng-model is null or invalid in select box and select first valid option

我有成百上千個這樣的案例(因此,修復程序必須是全局的,而不僅限於此特定示例)

有很多這樣的選擇框:

<select ng-model="selectedItem">
 <option ng-repeat="item in items | filter:attributes" value="{{item.id}}">{{item.name}}</option>
</select>

selectedItem變量為null(並且始終將其初始化為null,在這種特殊情況下,不能在控制器中對其進行更改)。

我試圖找出一種方法來觀看全球所有<select>在視圖中的元素,看看是否ng-model該變量<select>null ,如果是null它設置為第一個有效選項在該選擇框中,每當范圍更改時,都需要檢查ng-model是否為null並自動選擇第一個有效選項。

要實現這一點的關鍵是,您可以定義多個具有相同名稱的Angular指令,並且所有這些指令都將針對匹配的元素運行。

這非常強大,因為它使您能夠擴展內置指令或第三方指令等的功能。

使用此方法,我能夠創建一個select指令,只要模型值為null,它將在列表中選擇第一個有效選項。

但是,如果您從列表中刪除選定的項目(它返回為空白),它不會做的一件事就是應付。 但希望這足以讓您入門。

 var app = angular.module('stackoverflow', []); app.controller('MainCtrl', function($scope) { $scope.selectedItem = null; $scope.items = [1, 2, 3, 4].map(function(id) { return { id: id, visible: true, text: 'Item ' + id }; }); }); app.directive('select', function() { return { restrict: 'E', require: '?ngModel', link: function($scope, $elem, $attrs, ngModel) { // don't do anything for selects without ng-model attribute if (!ngModel) return; // also allow specifying a special "no-default" attribute to opt out of this behaviour if ($attrs.hasOwnProperty('noDefault')) return; // watch the model value for null var deregWatch = $scope.$watch(function() { return ngModel.$modelValue; }, function(modelValue) { if (modelValue === null) { // delay to allow the expressions to be interpolated correctly setTimeout(function() { // find the first option with valid text var $options = $elem.find('option'), $firstValidOption, optionText; for (var i = 0, len = $options.length; i < len; i++) { optionText = $options.eq(i).text(); if (optionText !== '' && !optionText.match(/^(\\?|{)/)) { $firstValidOption = $options.eq(i); break; } } if ($firstValidOption) { $firstValidOption.prop('selected', true); ngModel.$setViewValue($firstValidOption.attr('value')); // trigger a digest so Angular sees the change $scope.$evalAsync(); } }, 0); } }); // clean up in destroy method to prevent any memory leaks var deregDestroy = $scope.$on('$destroy', function() { deregWatch(); deregDestroy(); }); } }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <div ng-app="stackoverflow"> <div ng-controller="MainCtrl"> <select ng-model="selectedItem"> <option ng-repeat="item in items | filter:{visible:true} track by item.id" value="{{item.id}}">{{item.text}}</option> </select> <p>Visible items:</p> <ul> <li ng-repeat="item in items track by item.id"> <label> <input type="checkbox" ng-model="item.visible">{{item.text}} </label> </li> </ul> </div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM