【问题标题】:How to append select angularjs with options json如何使用选项 json 附加选择 angularjs
【发布时间】:2018-01-06 06:20:16
【问题描述】:

这段代码实际上是在没有附加功能的情况下工作的,但是当我附加它时,我可以看到选择,但里面唯一的数据是括号 {{option1.nomcarac}}

我想附加并接收我的选项,看起来很简单,但今天我的大脑已经死了

【问题讨论】:

  • 你必须使用$compile服务和各自的$scope..like$compile(elementToAdd)($scope)..除了这个问题之外,从控制器进行DOM操作被认为是反模式..

标签: angularjs json append


【解决方案1】:

您的问题的解决方案是这样的:

var elem = angular.element("<select><option ng-repeat='option in options1' 
value='option1.nomcarac'>{{option.nomcarac}}</option></select>");
 $(".testo").append($compile(elem)($scope));

这里是 plunker 链接:https://plnkr.co/edit/lotJ3ndRIGDp5pQqqKH0?p=preview

但是您不应该遵循这种 jquery 方法将字段动态添加到角度形式中。相反,您可以做的是在要动态添加任意次数的输入字段上使用 ng-repeat,并为这些动态创建的输入的模型值设置输入数组。所以你可以做到这一点:

<div ng-repeat="item in selects">
    <select ng-model="item.value"><option ng-repeat='option1 in options1' 
     value='{{option1.nomcarac}}' >{{option1.nomcarac}}</option></select>
    <button ng-click="getValue(item)">get input value</button>
</div>

并且在控制器中具有如下功能:

$scope.addSelectItem = function(){
    fieldname = "Field " + count;
    $scope.selects.push({name: fieldname});
    count++;
}

您可以为另一种输入字段设置另一个 ng-repeat。因此,通过这种方式,将更干净地添加字段。 示例:https://plnkr.co/edit/nptQEOOxt7cAmHJ2sT30?p=preview

【讨论】:

  • 非常感谢您完整而全面的回答!
【解决方案2】:

如果您的 HTML 字符串包含角度表达式,那么您需要 使用 $compile。

根据$compile服务的Angular官方文档。编译服务为:

将 HTML 字符串或 DOM 编译成模板并生成模板 函数,然后可用于链接范围和模板 在一起。

HTML:

<div ng-controller="DemoController">
  <dynamic-element selectOption='htmlString'></dynamic-element>
</div>

指令:

(function(){
"use strict";
angular.module("CompileDirective", [])
  .directive('dynamicElement', ['$compile', function ($compile) {
      return { 
        restrict: 'E', 
        scope: {
            selectOption: "="
        },
        replace: true,
        link: function(scope, element, attrs) {
            var template = $compile(scope.selectOption)(scope);
            element.replaceWith(template);               
        }
      }
  }])
  .controller("DemoController", ["$scope", function($scope){
      $scope.htmlString = '<select><option ng-repeat='option1 in options1' 
value='option1.nomcarac'>{{option1.nomcarac}}</option></select>';
  }])

}());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-14
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多