【问题标题】:ngTagsInput with autocomplete in a form and add to dbngTagsInput 在表单中具有自动完成功能并添加到数据库
【发布时间】:2016-09-23 10:13:56
【问题描述】:

我一直在尝试在 html 表单中使用 ngTagsInput 及其自动完成功能 (mbenford.github.io/ngTagsInput/demos) 来在 Mongodb 中提交食谱。

基本上,我使用带有自动完成功能的 ngTagsInput 来查询我的配料数据库并在“配方中的配料”中显示配料标签。

效果很好,直到我保存了食谱,但配料没有保存。

我知道问题出在哪里,但我还没有找到解决方案。 这是我添加食谱页面的“成分”字段,没有 ngTagsInput,只是一个普通的文本字段:

<div class="form-group">
            <label for="ingredients">List of ingredients</label>
            <input type="text" class="form-control" id="ingredients" ng-model="form.ingredients">
        </div>

这里是使用 ngTagsInput 的“成分”字段(工作正常,但不保存):

<div class="form-group" ng-controller="recipeApiController">    
        <tags-input for="Ingredients" id="Ingredients" ng-model="tags" display-property="ingredientID" placeholder="Commence à taper le nom d'un ingrédient..." add-from-autocomplete-only="true">
        <auto-complete source="loadTags($query)"></auto-complete>
        </tags-input>
        </div>

因为我将 ng-model="form.ingredients" 替换为使用 ngTagsInput 所需的 ng-model="tags",所以在单击“添加配方”按钮时不会保存这些成分标签。

这是我的 recipeApiController 的“保存到数据库”部分,用于“添加食谱”表单页面:

$scope.addToDatabase = function(){
    RecipeApi.Recipe.save({}, $scope.form, 
    function(data){
        $scope.recipe.push(data);
    },
    function(err){
        bootbox.alert('Error: ' + err);
    });
}

你知道我该如何解决这个问题并保存这些标签吗?

提前谢谢各位。我不希望这篇文章太长,但如果您需要更多信息、代码,我会非常积极地提供它。这对我有很大帮助。

【问题讨论】:

    标签: angularjs ng-tags-input


    【解决方案1】:

    我在另一篇文章中找到了解决方案: https://stackoverflow.com/a/38383917/6858949

    基本上,我无法保存这些标签,因为 ng-model 在&lt;tags-input&gt; 标签内不起作用。因此,我使用这个人的指令将&lt;tags-input&gt; 更改为属性:

    <div elem-as-attr="tags-input"></div>
    

    这是指令代码

    app.directive('elemAsAttr', function($compile) {
    return {
    restrict: 'A',
    require: '?ngModel',
    replace: true,
    scope: true,
    compile: function(tElement, tAttrs) {
      return function($scope) {
        var attrs = tElement[0].attributes;
    
        var attrsText = '';
        for (var i=0; i < attrs.length; i++) {
          var attr = attrs.item(i);
          if (attr.nodeName === "elem-as-attr") {
            continue;
          }
          attrsText += " " + attr.nodeName + "='" + attr.nodeValue + "'";        
        }
    
        var hasModel = $(tElement)[0].hasAttribute("ng-model");
        var innerHtml = $(tElement)[0].innerHTML;
        var html = '<' + tAttrs.elemAsAttr  + attrsText + '>' + innerHtml + '</' + tAttrs.elemAsAttr + '>';
    
        var e = hasModel ? $compile(html)($scope) : html;
        $(tElement).replaceWith(e);
      };
    }
    }
    });
    

    我认为这不是最佳选择,但以我目前的代码知识,我很庆幸我找到了这个解决方案。 ✌?

    编辑: 我现在正在使用 ui-select:https://github.com/angular-ui/ui-select 并且绝对推荐它

    编辑: 我把代码放在密码框里

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      • 2014-09-28
      • 2016-01-03
      • 2017-04-24
      相关资源
      最近更新 更多