简体   繁体   中英

Dynamically passing HTML content to Angular directives as attributes

I am trying to dynamically load some HTML stored in a JSON file using Angular.

I am doing this by reading the JSON data into a scope and passing it to a directive that I wrote for loading HTML into the template.

Controller

.controller('testCtrl', function($scope, $http, $state){

    $http.get('views/foo.json').then(function(res){

      $scope.somehtml = res.data;

    });

}) 

Directive

.directive('loadHtml', function($compile){

        return {
        restrict: 'AE',
        scope: {
            content: "@",
        },
        link: function(scope, element, attrs) {
            scope.content = attrs.content;
            element.html(scope.content).show();
            $compile(element.contents())(scope);
        },
        template: '{{content}}'
    };

})

This works!

<load-html content="hello success"></load-html> 

This doesn't : (

<load-html content="{{somehtml}}"></load-html>

What am I missing here??

Found the solution myself, perhaps this helps someone:

I needed to "observe" the attribute value in the directive.

New Directive:

.directive('loadHtml', function($compile){

    return {
        restrict: 'AE',
        scope: {},
        link: function(scope, element, attrs) {

            attrs.$observe('content', function(val) { /* $observing the attribute scope */
                scope.content = val;
                element.html(scope.content).show();
                $compile(element.contents())(scope);
            })
        },
        template: '{{content}}'
    };
})

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