我在使用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"
someVariable
是一个字符串(请参见更新)。尽管它不是很优雅,但{{(myObject.someVariable + '').length}}
可以正常工作。似乎是 AngularJS 中的一个错误。谢谢 :-) - JuljanmyObject.someVariable
,但是(myObject.someVariable + '').length
在{{}}
中也不起作用,也不能像这样使用ng-if="(myObject.someVariable + '').length > 0"
。 - LuckyLikey