Angular JS 模板中使用 string.length 出现问题

14

我在使用AngularJS(版本为1.2.6)时遇到了问题。

由于某种我无法理解的原因,我无法访问存储在$scope中的字符串变量的length属性。

在模板中:

String '{{myObject.someVariable}}' has length '{{myObject.someVariable.length}}'.

在控制器中:

$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();
});

结果是:

String 'aaaa' has length ''.

在控制台中,我正确地看到了内容:“aaaa”,长度:“4”

这很让人烦恼,因为我根据字符串的大小显示(或不显示)模板的某些部分。

更新

$scope.myObject.someVariable是一个字符串。我在回调函数中添加了一个断点,并使用了两个监视器:

  • $scope.myObject.someVariable:"aaaa"
  • typeof($scope.myObject.someVariable):"string"
2个回答

24

变量someVariable是字符串吗?如果不是的话,在访问长度属性之前可能需要将其转换为字符串。一种简单的方法是将其与空字符串连接:

{{(myObject.someVariable + '').length}}

someVariable 是一个字符串(请参见更新)。尽管它不是很优雅,但 {{(myObject.someVariable + '').length}} 可以正常工作。似乎是 AngularJS 中的一个错误。谢谢 :-) - Juljan
1
我似乎有同样的问题,但这并不能解决我的问题。我可以绑定到 myObject.someVariable,但是 (myObject.someVariable + '').length{{}} 中也不起作用,也不能像这样使用 ng-if="(myObject.someVariable + '').length > 0" - LuckyLikey

0
你可以通过在作用域中设置一个手动观察器来解决这个问题,以更新一个变量的字符串长度。
$scope.$watch('myObject.someVariable',function(newValue) {
  $scope.myVariableLength = newValue.length; 
})

我更喜欢另一种解决方案,它不会用额外的变量污染$scope,但还是谢谢你的想法。 - Juljan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接