简体   繁体   English

ng-bind-html无法正常工作

[英]ng-bind-html not working as expected

a.html a.html

<div ng-bind-html="htmlElement()"></div>

controller.js controller.js

$scope.htmlElement = function(){ 
  var html = '<input type="text" ng-model="myModel" />'; 
  return $sce.trustAsHtml(html);
}

But when I want to get the value of the text input using 但是当我想使用获取文本输入的值时

alert($scope.myModel);

It says myModel is undefined. 它说myModel是未定义的。 It only happens when I add the text input dynamically. 仅当我动态添加文本输入时才会发生。

How can I get the value of that text input? 如何获得该文本输入的价值?

I suggest you use this DOM manipulation with directive instead. 我建议您改为使用带有指令的DOM操作。

In your controllers.js : 在你的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);
    }
});

In your HTML : 在您的HTML

<div ng-controller="myCtrl">
    <my-html><my-html>
    Your input: {{myModel}}
    <button ng-click="showInputText()">Show Input Text</button>
</div>

try this, http://plnkr.co/edit/A4HRCuTbJt21wEngH9HX?p=preview : 试试看, 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);
          }); 
        }
      };
    });

try to add the following css to your div / element 尝试将以下CSS添加到您的div /元素中

white-space: pre-wrap;
word-wrap: break-word;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM