是的,因为这Object
是的一部分,window/global
而angular无法根据范围评估该表达式。当您Object.keys
在绑定中指定时,angular尝试针对进行评估$scope
,但找不到。您可以将object.keys
root 的引用存储在rootScope中的某个实用程序中,并在应用程序中的任何位置使用它。
像这样的东西:
angular.module('yourApp',[deps...]).run(function($rootScope){
//Just add a reference to some utility methods in rootscope.
$rootScope.Utils = {
keys : Object.keys
}
//If you want utility method to be accessed in the isolated Scope
//then you would add the method directly to the prototype of rootScope
//constructor as shown below in a rough implementation.
//$rootScope.constructor.prototype.getKeys = Object.keys;
});
并将其用作:-
<span class="pull-right"> {{ Utils.keys(stations).length }} Stations</span>
好吧,这对于除隔离范围之外的所有子范围都可用。如果您打算在隔离范围内执行此操作(例如:-隔离范围指令),则需要Object.keys
在范围上添加引用,或者在范围内公开将返回长度的方法时。
或者更好的是,创建一个格式过滤器以返回密钥长度并在任何地方使用它。
app.filter('keylength', function(){
return function(input){
if(!angular.isObject(input)){
throw Error("Usage of non-objects with keylength filter!!")
}
return Object.keys(input).length;
}
});
并做:
{{ stations | keylength }}