角什么是访问NG重复指令内的总目标的最佳途径 [英] Angular what is the best way to access total objects within ng-repeat directive

查看:139
本文介绍了角什么是访问NG重复指令内的总目标的最佳途径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

访问thhe一个NG重复内的物品的长度似乎很简单。 {{} array.length}

但是,当你不得不遍历低谷的对象和你要知道总
对象,那么你没有一个角的事情吧。

我现在所做的是计算总的属性,并将其存储在一个变量。

  $ scope.totalPersons = Object.keys($ scope.data)。长度;

但是,当项目被添加到该对象的 totalPersons 未更新,
我改变了这种因此该值将被更新。

  $范围。$腕表($ scope.data,功能(为newValue,属性oldValue){
    $ scope.totalPersons = Object.keys($ scope.data)。长度;
});

但是,有没有更好的方式来访问你的模板总的对象?

 < UL>
    <李NG重复=(键,值)数据>
        {{键}} - {{值}} {{totalPersons}}
    < /李>
< / UL>


解决方案

通过创建自定义过滤器,返回 Object.keys 你可以得到对象键的长度

\r
\r

angular.module('customfilter',[])。过滤器('键' ,函数(){\r
  复位功能(OBJ){\r
    返回Object.keys(OBJ);\r
  };\r
});

\r

&LT;脚本SRC =htt​​ps://ajax.googleapis.com/ajax /libs/angularjs/1.2.23/angular.min.js\"></script>\r
\r
&LT; D​​IV NG-应用='customfilter'NG-的init =数据= {A:1,B:2}&GT;\r
&LT; P&gt;该数组:{{数据|键}}&下; / P&GT;\r
  &所述; P&gt;将阵列长度:{{(数据|键)。长度}}&下; / P&GT;\r
&LT; / DIV&GT;

\r

\r
\r

Accessing thhe the length of items within a ng-repeat seems simple. {{array.length}}

But when you have to iterate trough objects and you have to know the total objects then you don't have a Angular thing for it.

What I did now is count the total properties and store it in a variable.

$scope.totalPersons =  Object.keys($scope.data).length;

But when items are added to the object the totalPersons is not updated so I changed this so the value will be updated.

$scope.$watch( $scope.data, function (newValue, oldValue) {
    $scope.totalPersons = Object.keys($scope.data).length;
});

But is there a better way to access the total objects in your template?

<ul>
    <li ng-repeat="(key, value) in data">
        {{key}} - {{value}}  {{totalPersons}}
    </li>
</ul>

解决方案

by creating a custom filter that return the Object.keys you can get the length of the object keys

angular.module('customfilter', []).filter('keys', function() {
  return function(obj) {
    return Object.keys(obj);
  };
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='customfilter' ng-init="data={a:1,b:2}">
<p>the array: {{ data | keys}}</p>
  <p>the array length: {{ (data | keys).length}}</p>
</div>

这篇关于角什么是访问NG重复指令内的总目标的最佳途径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆