How to associate a controller with dynamically added HTML?

I am injecting html inputs from a controller and I am trying to bind scope variables, but not working.

Here is my HTML code
:

    <div ng-controller='addHTML'>
       <div ng-bind-html="trustedHtml"></div>
       <code>{{user}}</code>
    </div>


CSS:

var app = angular.module('app',[]);
var addHTML = function ($scope,$sce) {
     $scope.user = {};
     $scope.user.someVariable = "";

    //inject some html
    $scope.html = '<input type="text" ng-model="user.someVariable">';
    $scope.trustedHtml = $sce.trustAsHtml($scope.html);

};

You can find it on the violin here: http://jsbin.com/miluguni/1/watch?html,js,output
When you enter the input, the region variables do not change.

+4
source share
1 answer

ngBindHtml the directive does not compile $ templates; it only inserts a template into the DOM.

I copied ngBindHtml( source code ) and added $ compile to it

new directive:

app.directive('compileHtml',['$sce', '$parse', '$compile', 
  function($sce, $parse, $compile){
  return {
    link: function(scope,element,attr){
      var parsed = $parse(attr.compileHtml);
      function getStringValue() { return (parsed(scope) || '').toString(); }            
      scope.$watch(getStringValue, function (value) {
        var el = $compile($sce.getTrustedHtml(parsed(scope)) || '')(scope);
        element.empty();
        element.append(el);        
      });       
    } 
  };
}]);

Template:

<div compile-html="trustedHtml"></div>

Here is a demo: http://jsbin.com/miluguni/3/edit

+4

Source: https://habr.com/ru/post/1527957/


All Articles