Question

How do you evaluate ng-attr for elements that have been inserted with ng-bind-html? JS Fiddle illustrating what I'm talking about here.

HTML:

<body ng-app="TestApp" ng-controller="TestCtrl">
    <div ng-bind-html='y | to_trusted'></div>
    <svg width="100" height="100">
        <path ng-attr-d="M{{x}},10L50,50L10,50Z" />
    </svg>
</body>

Javascript:

var app = angular.module("TestApp", []);

app.controller('TestCtrl', function ($scope, $interval) {
    $scope.y = '<svg width="100" height="100"><path ng-attr-d="M{{x}},10L50,50L10,50Z"/></svg>';
    $scope.x = 10;
});

app.filter('to_trusted', ['$sce', function ($sce) {
    return function (text) {
        return $sce.trustAsHtml(text);
    };
}]);

The ng-attr-d in the second <path> is evaluated, but the first is not.

Was it helpful?

Solution

Here's how this might look as a directive...

  • restrict: 'E': This directive is used as an element
  • x: '=': property on the isolated scope passed in as an attribute
  • template is the template

.

app.directive('myPath', function () {
    return {
        restrict: 'E',
        scope: {
            x: '='
        },
        template: '<svg width="100" height="100"><path ng-attr-d="M{{x}},10L50,50L10,50Z"/></svg>'
    };
});

And it can be used like this...

<my-path x="x"></my-path>

JsFiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top