2016-10-13 78 views
2

我想創建動態表單。在我的控制我創建一個字符串

var str = "<input type='text' value='" + $scope.selectedData.code + "' class='form-control' />"; 
$scope.htmlString = $sce.trustAsHtml(str); 

,並在我的html頁面

<div ng-bind-html="htmlString"></div> 

我得到的值,但不具約束力。 我也試用

var str = "<input type='text' ng-model='" + $scope.selectedData.code + "' class='form-control' />"; 
$scope.htmlString = $sce.trustAsHtml(str); 

也不起作用。任何人都可以知道這個工作如何?

回答

3

HTML:

添加一個指令:compile-template

<div ng-bind-html="htmlString" compile-template></div> 

JS:

angular.module('ngApp', ['ngSanitize']) 
.controller('controller1', ['$scope','$sce', function($scope, $sce) { 
    var str = "<input type='text' ng-model='" + $scope.selectedData.code + "' class='form-control' />"; 
    $scope.htmlString = $sce.trustAsHtml(str); 
}]) 
.directive('compileTemplate', function($compile, $parse){ 
    return { 
     link: function(scope, element, attr){ 
      var parsed = $parse(attr.ngBindHtml); 
      function getStringValue() { 
       return (parsed(scope) || '').toString(); 
      } 

      // Recompile if the template changes 
      scope.$watch(getStringValue, function() { 
       $compile(element, null, -9999)(scope); // The -9999 makes it skip directives so that we do not recompile ourselves 
      }); 
     } 
    } 
}); 
+0

我愛你老兄!現在完美的作品! TY! – GomuGomuNoRocket

+0

開心!!我可以幫助,享受:) – Aks1357