$compile on dynamic html

Check how the $watch is looking at the value passed to the bind attr value of the div

by johnwun

HTML

<script src="http://ci.angularjs.org/job/angular.js-angular-master/ws/build/angular.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://ci.angularjs.org/job/angular.js-angular-master/ws/build/angular-sanitize.js"></script>
<div ng-app='myApp' ng-controller="UpdateModelCtrl" id="dynamicFormOptions">
    Property One: <input type="text" ng-model="model.one"/>
    <div angular-html-bind="formOptions"></div>
    <button class="btn" ng-click="getExtraFormOptions()">Load Extra Options</button>
    <hr/>
    <pre>{{model | json}}</pre>
    <br />{{formOptions}}
    <br/> <div>{{options | json}}</div>
</div>

CSS

body {padding: 10px;}

JavaScript

function UpdateModelCtrl($scope, $http) {
    $scope.model = {
        name: 'the model'
    };
    
    $scope.getExtraFormOptions = function() {
        // Just to simulate an ajax call
        $http.post('/echo/html/', 'test data').success(function(data) {
            var options = [];

            options.push('Property Two: <input type="text" ng-model="model.two" /><br/>');
            options.push('Property Three: <input type="text" ng-model="model.three" )/>');
            $scope.formOptions = options.join('');
        });
    };
}

angular.module('myApp', []).directive('angularHtmlBind', function($compile) {
    return function(scope, elm, attrs) {
        scope.$watch(attrs.angularHtmlBind, function(newValue, oldValue) {
            if (newValue && newValue !== oldValue) {
                elm.html(newValue); 
                $compile(elm.contents())(scope);
            }
        });
    };
});