How to Assign value with ng-change in angular js

2020-05-25 07:35发布

问题:

I have simple drop-down bind with angular model

<select ui-select2="{allowClear:true}" ng-model="product.Id" ng-change="{value = product.Id == 0}" data-placeholder="Select Warranty">
      <option></option>
      <option ng-repeat="product in products" value="{{product.Id}}">{{product.Code}}</option>
</select>

How i can assign value depending on some condition in ng-change?

回答1:

Your selected value is defined as ng-model. On ng-change you can call a method from the controller and provide the "selected" ng-model to this method.

Here is an example:

<select                                               
        ng-model="product.Id"
        ng-options="filter as filter.name for filter in groupList"
        ng-change="changeItem(product.Id)"
         ></select>

Controller

$scope.changeItem = function(iem){

}

As a side note, I would use ng-options instead of <option ng-repeat.....



回答2:

Add a function to the scope that checks the condition and assigns the value if it is true. Simply call this function from ng-change.