I am currently working on a task that involves counting the number of characters within an element. However, the element contains bindings (e.g. {{data.username}}) and I need to determine the string length after the binding has been resolved.
My initial approach is to create an attribute directive and simply use .text().length
on the element passed into the "link" function – as shown below:
This is my current progress:
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>Counting Characters</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js"></script>
</head>
<body ng-controller="TestCtrl">
<div count-chars>{{person.firstName}} {{person.lastName}}</div>
<script>
var app = angular.module('app', []);
app.controller('TestCtrl', function ($scope) {
$scope.person = {
firstName: "James",
lastName: "Smith"
};
});
app.directive('countChars', [function(){
return {
link: function(scope, elem, attrs) {
console.log(elem.text());
console.log(elem.text().length);
}
};
}]);
</script>
</body>
</html>
The issue here is that it currently only displays the string before any bindings take place (as seen in the current console.logs
). What I aim to achieve is to receive James Smith
with 11
characters, yet the output shows
{{person.firstName}} {{person.lastName}}
and 40
characters instead.
Any suggestions on how to solve this?