【问题标题】:Binding an input field using ngModel through $sce service通过 $sce 服务使用 ngModel 绑定输入字段
【发布时间】:2015-10-20 17:33:29
【问题描述】:

我的问题可能有点令人困惑,我会尽量使其简单。我正在尝试使用cheerio.js 抓取网站,仅提取输入字段,将它们发送到我的前端,渲染它们并使用ng-model 将它们绑定到我的控制器上的值。出于安全原因,Angular 不会只让我显示原始 html,所以我通过 $sce.trustAsHtml() 和 ng-bind-html 发送它。当我尝试使用 ng-model 将该输入字段绑定到控制器上的值时,我的问题就出现了。它只是不起作用,我不知道它是否与 $sce 有关,或者我的方法是否全错。

控制器:

app.controller('homeCtrl', function ($scope, $sce, ScraperFactory) {

    $scope.value

    $scope.renderHtml = $sce.trustAsHtml('<input type="text" ng-model="value"/>')

});

HTML:

<section id="home">

    <pre> value = {{value}}</pre>

    <input type="text" ng-model="value" />

    <p ng-bind-html="renderHtml"></p>

</section>

pre 和 first 输入按预期工作。

【问题讨论】:

  • 编译服务可能在这里工作尝试这样的事情 this $scope.renderHtml = $compile($sce.trustAsHtml('' ))
  • 看这里你会找到你的答案,你需要告诉 Angular 将你的 ng-model 绑定到你的原始 html 中,使用 $compile 的指令。 stackoverflow.com/a/24563545/861206
  • 天哪,这行得通。这几乎看起来很神奇哈哈。谢谢!
  • 没看到这两个cmet真棒!!
  • 好的,所以它在一切都同步的情况下工作。但是当我在从后端异步获取代码的部分中添加时,ngmodel 不再起作用。 html 再次显示,但它没有连接到控制器值。我需要调用 $scope.$digest() 什么的吗?

标签: javascript angularjs scope controllers angular-ngmodel


【解决方案1】:

创建一个将 html 作为输入的自定义指令,然后简单地将编译后的 html 附加到元素中。您可以通过嵌入来做一些更有趣的事情,但这里有一些代码和一个有效的 plunk。

// js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $sce, $compile) {
  $scope.name = 'World';

  $scope.value;

  $scope.html = '<input  compile type="text" ng-model="value"/>';

});

app.directive("compileHtml", function( $compile) {
    return {
        restrict: "A",

        link: function (scope, element, attributes) {

            element.append($compile(attributes.compileHtml)(scope));

        }
    }
});

// html 

<section id="home">

    <pre> value = {{value}}</pre>

    <input type="text" ng-model="value" />

    <p compile-html ={{html}}></p>

</section>

http://plnkr.co/edit/XSGnyMGNa1vb4dB2z9wH?p=preview

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多