我是一个相当新的创建指令,这个指令可以帮助我整个应用程序。我基本上想要创建一个预先填充选项的自包含select元素指令。对于最终结果,我想要做的就是将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
提前感谢您的时间和帮助。
答案 0 :(得分:2)
"
属性中的ngOption
转义错误。适当的一个是:
template: [
'<select ',
'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(''),
演示: http://plnkr.co/edit/RLGc9dAElD1wpLN8uPm0?p=preview
另请注意,require
不是required
。而且由于您错误地输入了它 - 您可以将它们全部删除,在您的情况下不需要它(您使用范围ngModel: '='
绑定)。