2015-10-20 42 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

相關問題