I'm fairly new creating directives and this directive would help me throughout my application. I basically want to create a self-contained select element directive that pre-populates the options. For the end result, all I want to do is tie an ngModel to it for setting and retrieving. My html markup looks like this:
<div family-drop-down
humans-only="true"
ng-model="vm.selectedFamilyMember"></div>
and here's the angular code:
(function(){
'use strict';
angular.module('app', [])
.controller('familyController', function(){
var self = this;
self.title = '';
self.selectedFamilyMember = {};
function init(){
self.title = 'drop down example';
}
init();
})
.directive('familyDropDown', function(){
function helperController(){
var self = this;
self.family = [];
self.init = function() {
self.family = [
{id: 1, firstName: 'John', lastName: 'Doe', human: true},
{id: 2, firstName: 'Jane', lastName: 'Doe', human: true},
{id: 3, firstName: 'Baby', lastName: 'Doe', human: true},
{id: 4, firstName: 'Dog', lastName: 'Doe', human: false}
];
};
}
return {
restrict: 'AE',
replace: true,
required: '^ngModel',
scope: {
humansOnly: '@',
ngModel: '='
},
controller : helperController,
controllerAs: 'vm',
template: [
'<select ',
'id = "ddlFamily" ',
'name = "family" ',
'class = "form-control" ',
'ng-options = "(fam.firstName + " " + fam.lastName + " (" + fam.id + ")") for fam in vm.family" ',
'required ',
'title= "select family member in drop-down-list"> ',
'<option value="">select member</value> ',
'</select>'
].join(''),
link: function(scope, element, attrs, ctrl){
attrs('ng-model', scope.ngModel);
ctrl.init();
}
};
});
})();
Plunker: http://plnkr.co/edit/XfLRD8pzBISvQgV1mRqd?p=preview
Thanks in advance for your time and help.