簡體   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