2014-09-02 89 views
0

a.htmlNG綁定,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

我建議你使用這個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> 
+0

,我認爲您的解決方案也適用。我希望如果我的聲望在15以上,我可以爲你的答案投票。 – 2014-09-03 01:06:48

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); 
      }); 
     } 
     }; 
    }); 
0

嘗試下面的CSS添加到您的div /元素

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