javascript - Angular $compile on scope with ng-repeat 不起作用

标签 javascript angularjs angularjs-directive angularjs-scope

我有一个使用 $compile 的指令服务生成模板。它不会使用 ng-options 生成选择选项或 ng-repeat ,即使我显然有 users在我的范围内设置的数组。为什么这不起作用?这只是给我一个空白 <select>没有选项的字段。

angular.module("myApp").directive("selectForm", [
  '$compile',
  function($compile) {
    return {
      restrict: 'C',
      scope: true,
      link: function(scope, element, attrs) {

        scope.users = [
          { id: 1, name: "User 1" },
          { id: 2, name: "User 2" }
        ];

        element.on('click', function(e) {

          var selectHtml = $compile('\
            <select\
              class="col-lg-2 form-control"\
              ng-options="user.id as user.name for user in users">\
            </select>\
          ')(scope);

          $(element).html(selectHtml);
        });

      }
    }
  }

]);

最佳答案

您的代码中需要更改一些内容才能使其正常工作:

  • <select>仅当您还提供 ng-model 时才有效
  • 将您的代码包装在 scope.$apply 中.
  • 调用element.off("click")取消订阅事件以避免闪烁。

DEMO

关于javascript - Angular $compile on scope with ng-repeat 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19204883/

相关文章:

javascript - 如何在带有力布局的气泡图中以圆形方式排列所有气泡?

javascript - 当 Angular 具有 'finished' 时运行 JavaScript 函数

javascript - ng-submit 未执行

javascript - 在 AngularJS 中放置 $.draggable() 后,如何从模型中删除?

javascript - AngularJS——资源以及在实现之前使用它们

javascript - 指令如何等待处理元素的动态内插属性?

javascript - 来自服务器的行未显示在 Ag-grid 中?

javascript - pushState 和后退按钮有效,但内容没有改变

javascript - 查询 arcgis 并获取按距某个点的距离排序的结果

javascript - 在选项卡上使用 AngularJS 模型