As someone who is relatively new to creating directives, I am looking to develop a directive that will assist me in my application. What I aim to achieve is a select element directive that comes pre-populated with options and is self-contained. All I need to do in the end is connect an ngModel to it for data handling purposes. Here is an example of how my HTML markup looks:
<div custom-select
filter-by-humans="true"
ng-model="vm.selectedItem"></div>
Below is the AngularJS code snippet associated with this:
(function(){
'use strict';
angular.module('app', [])
.controller('customController', function(){
var self = this;
self.title = '';
self.selectedItem = {};
function initialize(){
self.title = 'Custom select example';
}
initialize();
})
.directive('customSelect', function(){
function helperCtrl(){
var self = this;
self.options = [];
self.init = function() {
self.options = [
{id: 1, name: 'Option 1'},
{id: 2, name: 'Option 2'},
{id: 3, name: 'Option 3'},
{id: 4, name: 'Option 4'}
];
};
}
return {
restrict: 'AE',
replace: true,
require: '^ngModel',
scope: {
filterByHumansOnly: '@',
ngModel: '='
},
controller : helperCtrl,
controllerAs: 'vm',
template: [
'<select ',
'id = "ddlOptions" ',
'name = "options" ',
'class = "form-control" ',
'ng-options = "opt.name for opt in vm.options" ',
'required ',
'title= "select an option from the list"> ',
'<option value="">select an option</value> ',
'</select>'
].join(''),
link: function(scope, element, attrs, ctrl){
attrs('ng-model', scope.ngModel);
ctrl.init();
}
};
});
})();
Plunker Demo: http://plnkr.co/edit/XfLRD8pzBISvQgV1mRqd?p=preview
Thank you for your assistance and time.