2015-10-20 41 views
1

我的问题可能有点令人困惑,我会尽量使其尽可能简单。我试图用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> 

预并如预期第一输入工作。

+0

编译服务可能会在这里工作尝试这样的事情这$ scope.renderHtml = $编译($ sce.trustAsHtml(“')) – TimCodes

+0

在这里看看你会发现你的答案,你需要告诉angular使用$ compile的指令来将你的ng-model绑定到原始html中。 http://stackoverflow.com/a/24563545/861206 – rbinsztock

+0

哦,我的上帝,工作。它几乎看起来很神奇哈哈。谢谢! – JN18

回答

0

创建一个自定义指令,该指令将html作为输入,然后将编译后的html附加到元素。你可以做一些更有趣的事情,但这里有一些代码和工作量。

// 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

相关问题