AngularJS + Select2(多个 - 标签) - 有时会显示其他标签

问题描述 投票:0回答:1

我正在使用AngularJS + select2(不是ui-select)。

然后在我看来,我有:

<select 
name="rubros" 
id="rubros" 
class="select2 form-control"
ng-model="vm.comercio.tags" 
ng-options="rubro.nombre for rubro in vm.rubros track by rubro.id"
multiple>
</select>

如您所见,select绑定到名为“comercio.tags”的变量,即一个对象数组。

嗯,这是有趣的事情:有时会显示标签,有时它们不显示。即使绑定工作正常。

行为是随机的;我可以在浏览器中按F5,错误出现并随机出现。

请看一下图片:

enter image description here

enter image description here

enter image description here

标签由get请求($ http)检索。

我不知道这里发生了什么。因为行为是随机再现的。

更新:

添加帮助成员请求的代码

//controller initialization before this

var scope = this;

var id = $routeParams.id;   //the ID of the commerce/store I want to edit (preload) in the page

//variable where I save the retrievedcommerce/store
scope.comercio = {
    tags:[]
};

/*
    HTTP request to retrieve the commerce/store with "id"
    The model retrieved has a tags attribute that is correctly filled (as you can see in the images, 
    in the input on top of the select2, I used to debug)
*/

$http.get("http://localhost:8000/api/comercio/" + id).then(function (response) {

    scope.comercio = response.data.model;

},
function (response) {

    scope.comercio = null;

});

//other controllers instructions and declarations
javascript angularjs tags jquery-select2 jquery-select2-4
1个回答
0
投票

正如人们所建议的那样,这个问题的原因是因为select2是一个jQuery插件,我们必须将它附加到角度“refresh”/ compile / digest / watch ... cycle ..换句话说,我们需要将select2附加到angularJS应用程序生命周期。

我们该怎么做呢 ?使用指令。官方文档非常广泛,但您可以通过这一小段代码欣赏解决方案。

app.directive("appSelect2", function($timeout) {

    return {
        restrict: "A",
        link: function (scope, element, attrs) {
            jQuery(element).select2();

            scope.$watch(attrs.ngModel, function () {
                $timeout(function () {
                    element.trigger('change.select2');
                }, 100);
            });

        }
    };
});

使用此指令,并将“app-select2”属性添加到html中声明的select2输入...它完美地工作。

非常感谢提供的帮助,非常感谢。

© www.soinside.com 2019 - 2024. All rights reserved.