您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

无法在angularjs中调用Object.keys

无法在angularjs中调用Object.keys

是的,因为这Object是的一部分,window/global而angular无法根据范围评估该表达式。当您Object.keys在绑定中指定时,angular尝试针对进行评估$scope,但找不到。您可以将object.keysroot 的引用存储在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 }}

其他 2022/1/1 18:13:36 有734人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶