不同条件下的ng模型

时间:2018-05-04 11:12:41

标签: javascript arrays angularjs

我有两个不同的数组:

var oldarr = ['one','two','three'];

var newarr = ['four','five','six'];

var condi = 1 / 0;

我使用数组值作为ng-model作为选择下拉列表的选项值。但是我想根据cond变量的值使用不同的数组,这意味着:如果condi是1,我将使用ng-model = oldarr而vif confi是2,我将使用ng-model = newarr。

我的下拉如下。有人可以建议我怎么做?

<select ng-model="oldarr " ng-selected="{{defaultvalue == selectedslastatus}}">
  <option ng-repeat="vals in oldarr ">{{vals }}</option>
</select>

2 个答案:

答案 0 :(得分:2)

我认为最好的方法是使用中间数组。

(实际上这可以通过 select m, sum(rlc), sum(rvatlc), sum(rtotlc), sum(clc), sum(cvatlc), sum(ctotlc) from( (select decode(j.consolno,null,j.shpno,j.consolno) m, sum(nvl(r.amtlc,0)) rlc, sum(nvl(r.vatamtlc,0)) rvatlc, sum(nvl(r.amtlc,0))+sum(nvl(r.vatamtlc,0)) rtotlc, 0 clc, 0 cvatlc, 0 ctotlc from job j full join revenue r on j.unid=r.job_unid where j.voidby is null and decode(j.consolno,null,j.shpno,j.consolno)='SHSEM00131' group by decode(j.consolno,null,j.shpno,j.consolno) ) union all (select decode(j.consolno,null,j.shpno,j.consolno) m, 0 rlc, 0 rvatlc, 0 rtotlc, sum(nvl(c.amtlc,0)) clc, sum(nvl(c.vatamtlc,0)) cvatlc, sum(nvl(c.amtlc,0))+sum(nvl(c.vatamtlc,0)) ctotlc from job j, cost c where j.voidby is null and j.unid=c.job_unid and decode(j.consolno,null,j.shpno,j.consolno)='SHSEM00131' group by decode(j.consolno,null,j.shpno,j.consolno) )) group by m; ng-showng-if来完成,但是如果你想要一个干净的HTML模板(View),你的数组结构是相同的,你可能想要将逻辑迁移到Controller)

像:

ng-switch

并执行在控制器中使用哪个数组的逻辑。

这是你的控制器的样子:

<select ng-model="modelArr" ng-selected="{{defaultvalue == selectedslastatus}}">
  <option ng-repeat="vals in modelArr ">{{vals }}</option>
</select>

答案 1 :(得分:1)

我只想用ng-show或类似的东西交换视图。假设condi并不总是布尔值(1或0),我建议ng-switch。这是一个例子:

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.condi = 1;
  $scope.oldarr = ['one', 'two', 'three'];
  $scope.newarr = ['four', 'five', 'six'];

  $scope.changeCondi = function() {
    $scope.condi = ($scope.condi == 1) ? 0 : 1;
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

  <button ng-click="changeCondi()">Change condi</button> : {{condi}}
  <div ng-switch="condi">
    <div ng-switch-when="1">
      <select ng-model="oldar">
        <option ng-repeat="vals in oldarr">{{vals}}</option>
      </select>
      Selected: {{oldar}}
    </div>

    <div ng-switch-when="0">
      <select ng-model="newar">
        <option ng-repeat="vals in newarr">{{vals}}</option>
      </select>
      Selected: {{newar}}
    </div>
  </div>

</div>
&#13;
&#13;
&#13;