Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  103] [ 4]  / answers: 1 / hits: 45443  / 11 Years ago, tue, december 31, 2013, 12:00:00

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


More From » angularjs

 Answers
73

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}}

[#73477] Sunday, December 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sergiobrayanc

Total Points: 162
Total Questions: 97
Total Answers: 94

Location: Lesotho
Member since Wed, Jun 2, 2021
3 Years ago
;