Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 模板中string.length的角度JS问题_Javascript_Angularjs - Fatal编程技术网

Javascript 模板中string.length的角度JS问题

Javascript 模板中string.length的角度JS问题,javascript,angularjs,Javascript,Angularjs,我对AngularJS(版本1.2.6)有一个问题 由于某些我无法理解的原因,我无法访问存储在$scope中的字符串变量的length属性 在模板中: String '{{myObject.someVariable}}' has length '{{myObject.someVariable.length}}'. 在控制器中: $scope.myObject = {} ; //asynchronuous loading of myObject SomeService.loadObject

我对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)
    :“字符串”

    • 某个变量
      是字符串吗?否则,在访问length属性之前,可能必须将其强制转换为字符串。任何简单的方法都是用空字符串连接它:

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

      您可以通过在作用域中设置手动观察程序来解决此问题,以使用字符串长度更新变量:

      $scope.$watch('myObject.someVariable',function(newValue) {
        $scope.myVariableLength = newValue.length; 
      })
      

      someVariable
      是一个字符串(请参阅更新)。虽然它不是很优雅,
      {{(myObject.someVariable+''.length}}
      工作正常。似乎是AngularJS中的一个bug。谢谢:-)我似乎也有同样的问题,但这并不能解决我的问题。我可以绑定到
      myObject.someVariable
      但是
      (myObject.someVariable+“”)。length
      {}
      中也不起作用,也不喜欢
      ng if=“(myObject.someVariable+”).length>0“
      我更喜欢另一种解决方案,它不会用额外的变量污染
      $scope
      ,但谢谢你的想法。