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

时间:2016-05-19 06:19:51

标签: javascript angularjs angularjs-ng-repeat

我对一个对象的数据值进行了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所有错误。

3 个答案:

答案 0 :(得分:3)

您可以通过将第一个键与第二个键分开(<li><span ng-bind="number.first/number.second"></span></li>)或使用控制器中的getter来实现此目的。

  

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

&#13;
&#13;
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
    }
  }];
});
&#13;
<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>
&#13;
&#13;
&#13;

Fiddle Demo

答案 1 :(得分:1)

如果您不需要对象中的第三个数字,但它可能是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>

答案 2 :(得分:1)

试试这个

&#13;
&#13;
var app = angular.module("app",[]);

app.controller("myctrl" , function($scope){
  
	$scope.numbers = [
        {
        first: 8,
        second: 5,
      
        },

        {
        first: 4,
        second: 5,
      
        }
	];

});

	
&#13;
   <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>
&#13;
&#13;
&#13;