Angular: Replacing text with Templates
want to replace certain letters (A,B,C,...) of a larger text with span tags which i css into nice symbols. Since I later reuse these tags I created an angular template directive
HTML
<div ng-app="foo">
<h1>Text</h1>
<div ng-controller="bar">
<div>{{text}}</div>
<h3>Legend</h3>
<div ng-repeat="kind in ['A','B','C']">
<symbol kind="kind"></symbol>
</div>
</div>
</div>
CSS
span {
height: 12px;
width: 12px;
}
.blue {
background: blue;
}
.red {
background: red;
}
.green {
background: green;
}
.yellow {
background: yellow;
}
JavaScript
angular.module('foo', [])
// the directive with template
.directive('symbol', function() {
return {
restrict: 'E',
replace: true,
template: '<span class="{{f1(kind)}}">{{f2(kind)}}</span>',
scope: {
kind: '='
},
link:function(scope,elem,attrs){
scope.f1=function(kind){
return kind.replace(/[A-Z]+/,"$&-test");
}
scope.f2=function(kind){
return kind.replace(/[A-Z]+/,"$&-testing testing");
}
}
};
})
// provider of text with symbols A, B, C, D
.controller('bar', ['$scope', function($scope) {
$scope.text = "Lorem ipsum dolor sit amet, A consectetur adipiscing elit. Nullam pretium B tellus a nisl blandit tristique. Vestibulum laoreet D pulvinar ante ac finibus. Fusce nisi mauris, pharetra B imperdiet dui eget, C rutrum tincidunt libero. Quisque pharetra nisl dictum, egestas sem sed, malesuada ex. D Suspendisse placerat faucibus tempor. donec pulvinar risus nunc, id venenatis tortor A sodales ac."
}])