4

I am inject html inputs from the controller and I am trying to bind the scope variables but its not working.

Here is my code
HTML :

    <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 fiddle here : http://jsbin.com/miluguni/1/watch?html,js,output
When typing in the input the scope variables isn't changed.

1
  • 1
    You need to run your HTML through the $compile service first. Commented Feb 20, 2014 at 17:36

1 Answer 1

4

ngBindHtml directive does not $compile templates, it only inserts the template to 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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.