ng-bind-html无法按预期工作

时间:2014-09-02 05:51:12

标签: javascript angularjs web angularjs-directive angular-ui

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未定义。它只在我动态添加文本输入时发生。

如何获取该文本输入的值?

3 个答案:

答案 0 :(得分:3)

我建议您使用带有指令的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>

答案 1 :(得分:0)

试试这个,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);
          }); 
        }
      };
    });

答案 2 :(得分:0)

尝试将以下css添加到div / element

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