Juljan
Juljan

Reputation: 812

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 :

Upvotes: 14

Views: 47108

Answers (2)

Michal Charemza
Michal Charemza

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

Michal Charemza
Michal Charemza

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

Related Questions