[英]ng-bind-html not working as expected
a.html
<div ng-bind-html="htmlElement()"></div>
controller.js
$scope.htmlElement = function(){
var html = '<input type="text" ng-model="myModel" />';
return $sce.trustAsHtml(html);
}
但是當我想使用獲取文本輸入的值時
alert($scope.myModel);
它說myModel是未定義的。 僅當我動態添加文本輸入時才會發生。
如何獲得該文本輸入的價值?
我建議您改為使用帶有指令的DOM操作。
在你的controllers.js
:
app.directive("myHtml", function(){
return {
restrict: 'E',
template: '<input type="text" ng-model="myModel" />',
link: function(scope, attr){
scope.myModel = 'Input text here';
}
}
});
app.controller('listCtrl', function($scope) {
$scope.showInputText = function(){
alert($scope.myModel);
}
});
在您的HTML
:
<div ng-controller="myCtrl">
<my-html><my-html>
Your input: {{myModel}}
<button ng-click="showInputText()">Show Input Text</button>
</div>
試試看, http : //plnkr.co/edit/A4HRCuTbJt21wEngH9HX?p=preview :
<div ng-bind-html="htmlElement()" compile-element></div>
....
module.directive("compileElement", function($compile){
return {
link: function(scope,element) {
scope.$watch(function(){
return element.html();
}, function() {
$compile(element.contents())(scope);
});
}
};
});
嘗試將以下CSS添加到您的div /元素中
white-space: pre-wrap;
word-wrap: break-word;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.