繁体   English   中英

将一个对象的属性值除以另一个(AngularJS)?

[英]Divide One Object Property Value by Another (AngularJS)?

我有一个ng-repeat对象的数据值。

<div ng-controller="myctrl">
  <ul ng-repeat="number in numbers">
    <li><span ng-bind="number.first"></span></li>
    <li><span ng-bind="number.second"></span></li>
    <li><span ng-bind="number.third"></span></li>
  </ul>
</div>

对象属性值之一取决于其他属性值的值(我希望第三值是第一/第二)。

.controller('myctrl', function($scope) {

    $scope.numbers = [
        {
        first: 8,
        second: 5,
        third: ? (I need this to be first / second)
        },

        {
        first: 4,
        second: 5,
        third: ? (I need this to be first / second)
        }
  ];

});

我一定把这个设置从根本上说是错误的,因为我很难想象它会这么困难,而且在过去的12个月中我通常没有与AngularJS或js一起工作,所以我有机会尝试ng-repeat都错了。

您可以通过将第一个键除以第二个键( <li><span ng-bind="number.first/number.second"></span></li> )来执行此操作,也可以在控制器中使用getter

getter是一种获取特定属性值的方法。

 var myApp = angular.module('myApp', []); myApp.controller('MainController', function($scope) { $scope.numbers = [{ first: 8, second: 5, get third() { return this.first / this.second } }, { first: 4, second: 5, get third() { return this.first / this.second } }]; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app='myApp' ng-controller="MainController"> <ul ng-repeat="number in numbers"> <li><span ng-bind="number.first"></span> </li> <li><span ng-bind="number.second"></span> </li> <li><span ng-bind="number.third"></span> </li> </ul> </body> 

小提琴演示

如果您不需要对象中的第三个数字,但它可以为null或者甚至根本没有它。 您可以这样做:

$scope.numbers = [
  {
    first: 8,
    second: 5,
    third: null /* you do not actually need this at all */
  },
  {
    first: 4,
    second: 5,
    third: null
  }
];

<ul ng-repeat="number in numbers">
  <li><span ng-bind="number.first"></span></li>
  <li><span ng-bind="number.second"></span></li>
  <li><span ng-bind="(number.first / number.second)"></span></li>
</ul>

尝试这个

 var app = angular.module("app",[]); app.controller("myctrl" , function($scope){ $scope.numbers = [ { first: 8, second: 5, }, { first: 4, second: 5, } ]; }); 
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body> <div ng-app="app"> <div ng-controller="myctrl"> <ul ng-repeat="number in numbers"> <li><span ng-bind="number.first"></span></li> <li><span ng-bind="number.second"></span></li> <li><span ng-bind="number.first/number.second"></span></li> </ul> </div> </div> </body> </html> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM