简体   繁体   中英

How do I create a DOM in function of an angular-js variable?

I have a function, renderFOO(value) , that returns a DOM element. How can I have that element rendered inside an AngularJS application, in function of a variable in a model?

I've managed to solve it using a directive:

<input type="range" ng-model="foo">
<foo></foo>

app.directive("foo", function(){
    return {
        restrict: "E",
        link : function(scope, elem, attr){
            scope.$watch("foo",function(periodo){
                elem[0].innerHTML = "";
                elem[0].appendChild(renderFOO(foo));
            });
        }}
});

But I think that is big and probably not idiomatic and the solution would be something like:

<input type="range" ng-model="foo">
<div>{{renderFOO(foo)}}</div>

Which does not work.

If I understand correctly, you should be able to leverage ngBindHtml in the ngSanitize module - offering the ability to bind DOM elements to some value. Observe the following simplified example...

<button ng-click="renderFoo()">render</button>
<div ng-bind-html="foo"></div>

$scope.renderFoo = function() {
    $scope.foo = '<span class="example">stuff</span>'
}

JSFiddle Link - simplified demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM