【发布时间】:2015-06-29 21:42:30
【问题描述】:
我是相当新的创建指令,这个指令将在我的整个应用程序中帮助我。我基本上想创建一个预先填充选项的自包含选择元素指令。对于最终结果,我要做的就是将 ngModel 绑定到它以进行设置和检索。我的 html 标记如下所示:
<div family-drop-down
humans-only="true"
ng-model="vm.selectedFamilyMember"></div>
这是角度代码:
(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
提前感谢您的时间和帮助。
【问题讨论】:
标签: javascript angularjs drop-down-menu angularjs-directive