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

后端 未结 2 360
北荒
北荒 2020-12-10 16:26

I need some help with an ng-model created with ng-bind-html. I have a JSON file in the server in which I have some html and some inputs like this:

*.json

<         


        
相关标签:
2条回答
  • 2020-12-10 16:44

    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>
    

    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题