HTML attribute binding in angularjs
I have this code:
<span data-icon="{{table.addIcon || ''}}"></span>
This range creates an icon like this:
However, I want to give the developer this directive the ability to define a new icon. However, the problem is that if I have this:
$scope.table.addIcon = ""
Instead of creating an element
<span data-icon=""></span>
he will create it
<span data-icon="&#xe070;"></span>
Which won't be able to add an icon, so instead:
What I have:
Is there a way to avoid angular to convert &
to &
?
Adding a solution
Thanks to miensol, the solution is:
.directive("changeIcon", function() {
var d = document.createElement("div");
return {
restrict: "A",
link: function($scope, $ele, $attrs) {
log($attrs);
var originalIcon;
$scope.decodedIcon = $attrs.icon;
do {
originalIcon = $scope.decodedIcon;
d.innerHTML = originalIcon;
$scope.decodedIcon = d.firstChild.nodeValue;
} while (originalIcon != $scope.decodedIcon);
$attrs.$set('data-icon', $scope.decodedIcon);
}
}
})
And it is used like this:
<span change-icon icon="{{table.addIcon || ''}}"></span>
source to share
I created a sample jsfiddle to try out the problem you described, but I am probably missing something.
I suspect you are seeing &
instead &
because the html view is encoded on the server .
It's pretty easy to decode html objects into javascript anyway . Consider the following example:
m.directive('icon', function(){
var div = document.createElement('div');
return {
scope: {
icon:'='
},
link: function($scope,$element,$attrs){
var originalIcon;
$scope.decodedIcon = $scope.icon;
do {
originalIcon = $scope.decodedIcon;
div.innerHTML = originalIcon;
$scope.decodedIcon = div.firstChild.nodeValue;
} while (originalIcon != $scope.decodedIcon);
console.log('data-icon', $scope.decodedIcon);
$attrs.$set('data-icon', $scope.decodedIcon);
}
};
});
You can play around with it here hopefully it helps to solve your problem.
source to share