Angular 附加 Html 代码中的 ng-model 不工作

Angular ng-model in appended Html code not working

这是我的代码。我在按钮 click.but 上动态添加 html 的地方,我提供的 ng-model 不起作用。

谁能解决我的问题

$scope.addParam = function(selected) {
  if (selected == "bucket_policy_privacy_status") {
    var myElement = angular.element(document.querySelector('#inputParameters'));
    myElement.append('<input type="text" style="width:220px" class="form-control" name="" disabled="" value=' + selected + '> <select class="form-control" style="width:196px" ng-model="fields.privacyStatus" ><option value="range">Range</option><option value="public">Public</option><option value="private">Private</option></select> <br><br>');
      $scope.$watch('fields.privacyStatus', function() {
        var privacy_status = $scope.fields.privacyStatus;
        alert();
        var status = {
          "term": {}
        }
        status.term[selected] = privacy_status;
        output.push(status);
      });
    $('#params option[value="bucket_policy_privacy_status"]').remove();
    $scope.input.select = "bucket_owner";
  }
};

我认为这行不通,您只添加了 dom,仅此而已,没有绑定。 一种方法是创建将执行此操作的指令,或者使用 "ng-hidden" 在模板中添加该输入,然后单击仅显示。

您需要更改一些内容:

动态插入 HTML 时,您需要使用 Angulars $compile 选项来评估 angular attributes/expressions。

在 DOM 添加元素后添加下面的行应该可以解决问题:

$compile(angular.element('.form-control'))($scope);

它基本上只是让我们 angular 知道有一些新东西应该评估并开始观看。

(不要忘记将 $compile 添加到您的模块依赖项中)。

除此之外,我假设您实际上已经在 $scope?

上添加了一个名为 fields 的对象

您可以做的另一件事是在您的表单上使用 ng-change 而不是使用 $watch。每当您的表单中的一个选择发生变化时,您绑定在 ng-change 上的函数就会被调用。

如需进一步阅读,请查看以下内容: https://docs.angularjs.org/api/ng/service/$编译