【问题标题】:AngularJS + Select2 (Multiple - Tags) - sometimes show tags others notAngularJS + Select2(多个 - 标签) - 有时会显示其他标签
【发布时间】:2018-06-07 13:23:50
【问题描述】:

我正在使用 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>

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

好吧,有趣的是:标签有时会显示,有时则不会。即使绑定正在工作。

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

请看图片:

标签由获取请求 ($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

【问题讨论】:

  • 由于 AngularJS 不控制渲染,您可能会遇到由请求返回所需时间可变导致的随机计时问题?你能显示 $http 代码吗?
  • 请注意,jQuery 不是 AngularJS 摘要循环的一部分。您可能需要将其包装在带有$timeout$apply 的指令中。 (比如this example
  • @Protozoid ,我刚刚添加了代码
  • @AlekseySolovey,我正在看,马上回来
  • 非常感谢大家,终于明白问题的原因了。

标签: javascript angularjs tags jquery-select2 jquery-select2-4


【解决方案1】:

正如人们所建议的那样,这个问题的原因是因为 select2 是一个 jQuery 插件,我们必须将它附加到 angular "refresh"/compile/digest/watch ...循环..换句话说,我们需要将 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 输入中......它可以完美运行。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    相关资源
    最近更新 更多