【发布时间】:2015-07-05 00:47:33
【问题描述】:
使用jquery-select2(not ui-select)和角度,我正在尝试将值设置为 ng-model。
我尝试过使用 $watch 和 ng-change,但在使用 select2 选择项目后似乎没有触发。
很遗憾,我使用的是购买的模板,无法使用 angular-ui。
HTML:
<input type="hidden" class="form-control select2remote input-medium"
ng-model="contact.person.id"
value="{{ contact.person.id }}"
data-display-value="{{ contact.person.name }}"
data-remote-search-url="api_post_person_search"
data-remote-load-url="api_get_person"
ng-change="updatePerson(contact, contact.person)">
客户端控制器:
$scope.updatePerson = function (contact, person) {
console.log('ng change');
console.log(contact);
console.log(person);
} // not firing
$scope.$watch("client", function () {
console.log($scope.client);
}, true); // not firing either
JQuery 集成:
var handleSelect2RemoteSelection = function () {
if ($().select2) {
var $elements = $('input[type=hidden].select2remote');
$elements.each(function(){
var $this = $(this);
if ($this.data('remote-search-url') && $this.data('remote-load-url')) {
$this.select2({
placeholder: "Select",
allowClear: true,
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: Routing.generate($this.data('remote-search-url'), {'_format': 'json'}),
type: 'post',
dataType: 'json',
delay: 250,
data: function (term, page) {
return {
query: term, // search term
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
return {
results: $.map(data, function (datum) {
var result = {
'id': datum.id,
'text': datum.name
};
for (var prop in datum) {
if (datum.hasOwnProperty(prop)) {
result['data-' + prop] = datum[prop];
}
}
return result;
})
}
}
},
initSelection: function (element, callback) {
// the input tag has a value attribute preloaded that points to a preselected movie's id
// this function resolves that id attribute to an object that select2 can render
// using its formatResult renderer - that way the movie name is shown preselected
var id = $(element).val(),
displayValue = $(element).data('display-value');
if (id && id !== "") {
if (displayValue && displayValue !== "") {
callback({'id': $(element).val(), 'text': $(element).data('display-value')});
} else {
$.ajax(Routing.generate($this.data('remote-load-url'), {'id': id, '_format': 'json'}), {
dataType: "json"
}).done(function (data) {
callback({'id': data.id, 'text': data.name});
});
}
}
},
});
}
});
}
};
任何建议将不胜感激! :)
更新
我已经设法将a plunk 放在一起,这似乎同样重现了问题 - 现在看起来好像 ng-watch 和 $watch 事件仅在第一次更改值时才被触发。 尽管如此,在我的代码中(以及在添加进一步的复杂性时,例如从集合中动态添加和删除时),它甚至似乎都没有触发一次。
再次,我们将不胜感激指向正确方向(或真正指向任何方向)的指针!
【问题讨论】:
-
你能分享一下jquery方面的集成吗?我怀疑您需要做更多的工作来处理 jquery-select2 发出的事件。
-
如何尝试使用普通的 JavaScript(或 jQuery)处理程序并使用
$scope.$apply,如$('.select2remote').on('change', function () { var value = $(this).value; $scope.$apply(function () { $scope.contact.person.id = value; }); })来观察输入 -
@JoeEnzminger 更新
-
@azium AFAIK $scope 在模块之外对我不可用。我错了吗?
标签: angularjs jquery-select2 angularjs-ng-change jquery-select2-3