Reputation: 2679
I have this template
<span highlight>{{player.Name}}</span>
and this directive
wcApp.directive('highlight', function() {
return {
restrict : 'A',
link : function (scope, element, attrs) {
var nameStr = element.text();
nameStr = $.map(nameStr,function(letter){
return letter == ' ' ? ' ' : letter;
});
element.html('<span>' + nameStr.join('</span><span>') + '</span>');
}
};
});
But it's not working. I want to grab the text in the span, break-up the letters and wrap each character in a span.
What am I doing wrong?
Upvotes: 0
Views: 79
Reputation: 2927
try
.directive('highlight', function() {
return {
restrict : 'A',
template: '<span ng-repeat="l in letters">{{ l.letter }}</span>',
link : function (scope, element, attrs) {
var nameStr = attrs.highlight;
nameStr = nameStr.split("");
var map = [];
var i=0, len=nameStr.length;
for (; i<len; i++) {
map.push({letter: nameStr[i] = nameStr[i].replace(" ", " ")});
}
scope.letters = map;
}
};
});
Upvotes: 1
Reputation: 37786
The problem is the binding, element haven't been compiled yet, there is diffrent way to solve this (prioritize you directive after compile, binding & compiling it yourself with the compileProvider)
wcApp.directive('highlight', function() {
return {
restrict : 'A',
link : function (scope, element, attrs) {
var nameStr = element.text();
alert(nameStr); // {{player.Name}}
nameStr = $.map(nameStr,function(letter){
return letter == ' ' ? ' ' : letter;
});
element.html('<span>' + nameStr.join('</span><span>') + '</span>');
}
};
});
Alternative solution:
<span highlight="player.name"></span>
...and js
wcApp.directive('highlight', function() {
return {
restrict : 'A',
scope: {highlight: "="},
link : function (scope, element, attrs) {
var nameStr = scope.highlight;
// alert(nameStr); // not {{player.Name}}
nameStr = $.map(nameStr,function(letter){
return letter == ' ' ? ' ' : letter;
});
element.html('<span>' + nameStr.join('</span><span>') + '</span>');
}
};
});
simpulton have written a very good blog post about this worth reading: http://onehungrymind.com/angularjs-sticky-notes-pt-2-isolated-scope/
Upvotes: 1