konapun
konapun

Reputation: 199

AngularJS - parse scope data as Angular expression

I need to create a directive which allows data passed in to contain angular expressions, such as the contrived example below (Codepen):

<div ng-controller="ctrl">
    <list-test data="data"></list-test>
</div>

Where data is defined as:

app.controller('ctrl', ['$scope', function($scope) {
    $scope.data = [
        '<input type="text" ng-model="testModel">',
        '{{testModel}}'
    ];
}]);

And my directive looks like:

app.directive('listTest', ['$sce', function($sce) {
    return {
        restrict: 'E',
        scope: {
            data: '='
        },
        template: [
            '<ul ng-repeat="item in data">',
                '<li ng-bind-html="escape(item)"></li>',
            '</ul>'
        ].join(''),
        link: function(scope) {
            scope.escape = function(item) {
                return $sce.trustAsHtml(item);
            };
        }
    };
}]);

I've tried modifying my linker to run the item through the compiler but this causes errors. I do know about ng-transclude but it doesn't fit my particular use case.

Upvotes: 0

Views: 92

Answers (1)

georgeawg
georgeawg

Reputation: 48968

Do something like:

scope.$watch("htmlList", function(value) {
    if (value) {
        childScope = scope.$new();
        childElement = $compile(htmlString(value))(childScope);
        elem.append(childElement);
    }            
});

Of course it gets more complicated if it is more than a one-time binding. In which case the code needs for remove the previous child element and destroy the previous child scope.

The DEMO on JSFiddle.

Upvotes: 1

Related Questions