无法在angularjs中调用Object.keys

Gar*_*yle 44 javascript angularjs angular-ui-bootstrap

我正在使用UI.Bootstrap手风琴,我已经定义了我的标题:

<accordion-group ng=repeat="(cname, stations) in byClient">
    <accordion-heading>
        {{ cname }} <span class="pull-right"> {{ Object.keys(stations).length }} Stations</span>
    </accordion-heading>
Run Code Online (Sandbox Code Playgroud)

当它显示Object.keys(stations).length解决方案为零.如果我在控制器中放入相同长度的呼叫,我会收回预期的计数.是否存在阻止方法调用在AngularJS中工作的内容?

手风琴的其余部分使用stations了预期的动作,所以我知道它正在被正确填充.该byClient数据结构基本上看起来像这样:

{
    "Client Name" : {
        "Station Name": [
            {...},
            {...}
        ]
    }
 }
Run Code Online (Sandbox Code Playgroud)

PSL*_*PSL 83

是的,那是因为Object是一部分window/global而且角度无法根据范围评估该表达式.当您Object.keys在绑定角度中指定尝试对其进行评估时$scope,它找不到它.您可以object.keys在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;

});
Run Code Online (Sandbox Code Playgroud)

并用它作为: -

<span class="pull-right"> {{ Utils.keys(stations).length }} Stations</span>
Run Code Online (Sandbox Code Playgroud)

除了隔离的范围之外,任何子范围都可以使用.如果您计划在隔离范围上执行此操作(例如: - 隔离范围指令),则需要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;
  }
});
Run Code Online (Sandbox Code Playgroud)

并做: -

{{ stations | keylength }}
Run Code Online (Sandbox Code Playgroud)

演示