我正在angularjs中实现jQuery select2。
HTML:
<input type="hidden" ng-model="multiselect" style="width:300px;" dev >
id {{multiselect.id}} // want to print selected items id
text {{multiselect.text}} //want to print selected items text
指令代码
app.directive('dev',[function(AutoCompleteService) {
return {
restrict: 'A',
link: function(scope, elem, attr, ctrl) {
$(elem).select2(
{
minimumInputLength:1,
multiple:true,
query:function(query)
{
var data={results:[]};
console.log("input string"+query.term);
data= scope.getmultiselectresult(query.term);
console.log("Data"+data.results.length);// nothing is return ..print length 0
for(var c=0;c<data.results.length;c++)
{
console.log("text"+scope.data.results.text+"id"+scope.data.results.id);
}
query.callback(data);
}
});
}
};}]);
控制器代码
$scope.getmultiselectresult = function(term) {
console.log("in controller getmultiselectresult..term" + term);
var results = [];
$http({
url : "rest/getMultiSelect",
method : "GET",
params : {
term : term
}
}).success(function(data) {
console.log("data.length" + data.length + "data" + data); //fetches data correctly
for (var i = 0; i < data.length; i++) {
$scope.data.results.push({
id : data[i].id,
text : data[i].text
});
console.log("id " + results[i].id + " name" + results[i].text);
}
});
return results;
};
我的问题是,我无法正确地将数据从控制器传递到指令链接器功能。而且我也想知道如何获取所选项目的ID和文本。
提前致谢
答案 0 :(得分:1)
我无法使用查询函数获得预期的行为。所以我尝试了select2的ajax,它适用于我。
Html代码
<input type="hidden" id="multiselect" ng-model="multiselect" style="width:200px;" dev>
<input type="button" value="OK" class="btn btn-primary" show>
指令代码
app.directive('show', [ function()
{
return {
restrict : 'A',
link : function(scope, elem, attr, ctrl) {
$(elem).click(
function() {
var dataset = $('#multiselect').select2('data');
console.log("dataset" + dataset + "dataset"
+ dataset.length);
for (var zz = 0; zz < dataset.length; zz++) {
console.log("id" + dataset[zz].id + "text>>"
+ dataset[zz].text);
scope.selectedEmpNo = dataset[zz].id;
scope.selectedName = dataset[zz].text;
}
scope.addRelAdmin(dataset);
});
}
};
} ]);
app.directive('dev', [ function() {
return {
restrict : 'A',
link : function(scope, elem, attr, ctrl) {
$(elem).select2({
minimumInputLength : 3,
multiple : true,
quietMillis : 1000,
ajax : {
url : "rest/getEmployees",
dataType : 'json',
data : function(term, page) {
return {
q : term
// search term
};
},
results : function(data) {
var myResults = [];
$.each(data, function(index, item) {
myResults.push({
id : item.personId,
text : item.firstName + " " + item.lastName
});
});
return {
results : myResults
};
}
},
});
}
};
} ]);