Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS issue with string.length in templates

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"
like image 446
Juljan Avatar asked Dec 31 '13 08:12

Juljan


1 Answers

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}}
like image 183
Michal Charemza Avatar answered Oct 01 '22 01:10

Michal Charemza