Reputation: 812
I have an issue with AngularJS (version 1.2.6).
For some reason that I could not understand I cannot access the length
property of a string variable stored in the $scope
.
In the template:
String '{{myObject.someVariable}}' has length '{{myObject.someVariable.length}}'.
In the controller:
$scope.myObject = {} ;
//asynchronuous loading of myObject
SomeService.loadObject(function(result)){
$scope.myObject = result ;
console.log("Content: '%s', length:'%i'",$scope.myObject.someVariable,$scope.myObject.someVariable.length);
$scope.$apply();
});
The result is :
String 'aaaa' has length ''.
In the console I correctly see Content:'aaaa', length:'4'
This is ennoying because I display (or not) some parts of the template depending on the string size.
Update
$scope.myObject.someVariable
is a string. I added a breakpoint in the callback function with two watches :
$scope.myObject.someVariable
: "aaaa"typeof($scope.myObject.someVariable)
: "string"Upvotes: 14
Views: 47108
Reputation: 27052
You could work around this problem by setting up a manual watcher in the scope, to update a variable with the length of the string:
$scope.$watch('myObject.someVariable',function(newValue) {
$scope.myVariableLength = newValue.length;
})
Upvotes: 0
Reputation: 27052
Is someVariable
a string? If not, you might have to cast it to a string before accessing the length property. Any easy way is to concatenate it with an empty string:
{{(myObject.someVariable + '').length}}
Upvotes: 24