При работе с ng-моделью и пользовательскими директивами вы можете указать ngModel
как требование, а затем автоматически получить доступ к другим директивам, таким как ngChange
и ngRequired
.Я обновил ваш план: http://next.plnkr.co/edit/VzYpZ2elmzV6XkbM?open=lib
HTML
<md-custom-select
ng-model="vm.SelectItems"
ng-change="vm.onselectchange()"
list="vm.ItemList">
</md-custom-selector>
JavaScript
var app = angular.module("MaterialApp", ["ngMaterial"]);
app.directive("mdCustomSelect", ["$compile", mdCustomSelect]);
function mdCustomSelect($compile) {
return {
restrict: "E",
require: {
ngModelCtrl: '^ngModel'
},
scope: {
ngModel: "<",
list: "=",
options: "<",
},
replace: true,
link: function(scope, element, attrs, controllers) {
scope.ngModelCtrl = controllers.ngModelCtrl;
var searchTemplate = '<md-select-header aria-label="Select Header" class="demo-select-header"><input aria-label="InputSearchBox" ng-keydown="$event.stopPropagation()" ng-model="searchTerm" type="search" placeholder="Search items" class="md-text"></md-select-header>';
var selectAllTemplate = '<div style="padding: 0px 0px 15px 5px; background-color: #efefef;"><md-checkbox class="md-warn" title="Select All" ng-model="checkAllChecked" ng-change="toggleSelectAll()">Check/Uncheck All </md-checkbox></div>';
var multiSelectGroupTemplate = '<md-option ng-value="item.ItemID" ng-repeat="item in ItemList | filter: searchTerm">{{item.ItemName}}</md-option>';
var completeTemplate = "";
completeTemplate += '<md-select multiple ng-model="ngModel" ng-change="valChanged()" data-md-container-class="selectdemoSelectHeader">';
completeTemplate += searchTemplate; //2 begin and end
completeTemplate += selectAllTemplate; //3 begin and end
completeTemplate += multiSelectGroupTemplate; //4 begin and end
completeTemplate += " </md-select>"; //1 end
element.html(completeTemplate);
$compile(element.contents())(scope);
},
controller: ["$scope", function($scope) {
var defaultValueProperty = ($scope.options == undefined || $scope.options.Value === undefined) ? "value" : $scope.options.Value;
var defaultTextProperty = ($scope.options == undefined || $scope.options.Text === undefined) ? "name" : $scope.options.Text;
$scope.isMultipleSelected = angular.isUndefined($scope.multiple) ? true : $scope.multiple;
$scope.checkAllChecked = false;
$scope.ItemList = [];
var rawItemList;
$scope.$watch("list", function(newValue) {
$scope.ItemList = newValue.map(item => {
return { ItemID: item[defaultValueProperty], ItemName: item[defaultTextProperty] };
});
}, true);
$scope.valChanged = function(){
$scope.ngModelCtrl.$setViewValue($scope.ngModel);
}
$scope.toggleSelectAll = function() {
if ($scope.checkAllChecked == false) {
$scope.ngModelCtrl.$setViewValue([]);
} else {
$scope.ngModelCtrl.$setViewValue($scope.ItemList.map(item => item.ItemID));
}
};
}]
};
}