Using jquery-select2 (not ui-select) and angular, I'm trying to set the value to the ng-model.
I've tried using $watch and ng-change, but none seem to fire after selecting an item with select2.
I have even tried with directive but unable to get model binding value using angular latest version form 1.6 and above 1.7x. plunker:sample code
<div class="col-md-6 service">
<select select2 class="form-control" name="service" id="service"
ng-model="selected" style="width: 200px;" required>
<option value="">--Select--</option>
</select></div>
Any advice would be greatly appreciated! :)
app.directive('select2', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
scope.dependentVals = {
party: ["service", "inputformat", "psa"],
service: ["inputformat", "psa"],
inputformat: ["psa"]
}
//$this becomes element
debugger
element.select2({
//options removed for clarity
// var pageLimitCount = 500, add_method = 'GET';
// $(".select2Dropdown").each(function () {
// $(this).select2({
ajax: {
url: 'data.json',
type: 'GET',
dataType: 'json',
delay: 250,
crossDomain: true,
processResults: function (data) {
debugger;
var myarr = []
for (var j in data) {
myarr.push({
'id': data[j].actualvalue,
'text': data[j].displayvalue
})
}
return {
results: myarr,
pagination: {
more: data.length >= 500
}
};
},
cache: true
},
placeholder: 'Select',
minimumInputLength: 0,
allowClear: true,
dropdownParent: $('.'+element.attr('name'))
});
element.on("select2:unselect", function (e) {
$('#uploadHere').css({
"pointer-events": "none",
"opacity": 0.5
});
for (var i in scope.dependentVals[element.attr('name')]) {
$("[name=" + scope.dependentVals[element.attr('name')][i] + "]").val("").trigger("change")
}
});
element.on("select2:select", function (e) {
$('#uploadBtn').val('')
$('#uploadHere').css({
"pointer-events": "none",
"opacity": 0.5
});
for (var i in scope.dependentVals[element.attr('name')]) {
$("[name=" + scope.dependentVals[element.attr('name')][i] + "]").val("").trigger("change")
}
});
// });
// });
element.on('change', function() {
console.log('on change event');
var val = element.value;
scope.$apply(function(){
//will cause the ng-model to be updated.
ngModel.setViewValue(val);
});
});
ngModel.$render = function() {
//if this is called, the model was changed outside of select, and we need to set the value
//not sure what the select2 api is, but something like:
element.value = ngModel.$viewValue;
}
}
}
});