CodeWithCoffee
CodeWithCoffee

Reputation: 1904

ng-model on different condition

I have 2 different array set as :

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

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

var condi = 1 / 0;

I am using array value as ng-model as options value for select dropdown. However I want to use different array on basis of value of cond variable, that means : if condi is 1, I will use ng-model = oldarr and vif confi is 2 , I will use ng-model = newarr.

My drop down is as below. can someone pls suggest me how can I do this ?

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

Upvotes: 0

Views: 382

Answers (2)

Sajjad Shahi
Sajjad Shahi

Reputation: 602

I think the best approach is to use a middle array.

(Actually this can be done by ng-show or ng-if or ng-switch but if you want a clean HTML Template (View) and your arrays' structures are the same you may want to migrate the logic to Controller)

like:

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

and do the logic of using which array in your controller.

This is how your controller may look like:

// 
$scope.$watch('condi', function (){
    if (condi === true)
        $scope.modelArr = newArr;
    else
        $scope.modelArr = oldArr;
})

Upvotes: 2

Aleksey Solovey
Aleksey Solovey

Reputation: 4191

I would simply swap the views with ng-show or something similar. Assuming that condi is not always a boolean (1 or 0), I suggest ng-switch. Here is an example:

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;
  }
});
<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>

Upvotes: 1

Related Questions