How to watch for ng-model created with ng-bind-html

不羁的心 提交于 2019-11-28 11:15:28

You have to compile dynamically created elements to let angular know about them.

Directive which can do that may look like this one:

app.directive('compile',function($compile, $timeout){
    return{
        restrict:'A',
        link: function(scope,elem,attrs){
            $timeout(function(){                
                $compile(elem.contents())(scope);    
            });
        }        
    };
});

$timeout is used to run compile function, after ng-bind-html do its job.

Now you can just simply put compile as attribute of div with ng-bind-html:

<div class="questions" ng-repeat="item in questions" ng-show="questions.length" >
   <div ng-bind-html="item.question"></div>
   <div compile class="options" ng-bind-html="item.options"></div>
</div>

Fiddle: http://jsfiddle.net/nZ89y/7/

leehow Hi

javascript:

app.controller('demoController', function($rootScope, $scope, $http, $compile){
var arr = [
    '<div>I am an <code>HTML</code>string with <a href="#">links!</a> and other <em>stuff</em></div>'
    ,'<div>name: <input ng-model="user.name" /></div>'
    ,'<div>age: <input ng-model="user.age" /></div>'];

    $scope.user={};
    $scope.testChange2 = function(){
        var compileFn = $compile( arr[Number.parseInt(Math.random()*10)%3] );
        var $dom = compileFn($scope);
        $('#test').html($dom);
    };
});

html:

<div ng-controller="demoController">
    <button type="button" class="btn w-xs btn-info" ng-click="testChange2();" >test2</button>
    <hr/>
    <div id = "test"></div>
    <hr/>
    <div>user:{{user}}</div>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!