AngularJS-如何将ng-model变量重置为Null

时间:2019-05-13 08:22:06

标签: angularjs angularjs-scope angularjs-select

在AngularJS中,我有以下示例代码:

<select style="margin-left:5px;width:60px" id="product" ng-model="output.product">
<select style="margin-left:5px;width:60px" id="status" ng-model="output.status">

在我的UI屏幕中,我有一个按钮,用户可以在其中重置productstatus的选择下拉值,但是我不确定如何重置ng-model范围的输出值output.productoutput.status为null。

我尝试过scope.output = "";,但这似乎不起作用。

同样,我使用的是AngulaJS(v1.1)。

2 个答案:

答案 0 :(得分:1)

我不会为AngularJS V1.1编写答案,因为不再支持该版本。参见AngularJS Version Support Status

对于1.7版,通过将模型设置为null来重置选择:

  $scope.reset = function() {
      $scope.choice.product = null;
      $scope.choice.status = null;
  }; 

演示

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.choice = {};
  $scope.productChoices = ['product A', 'product B', 'product C', 'product D', 'product E'];
  $scope.statusChoices = ['active', 'pending', 'completed', 'cancelled'];

  $scope.reset = function() {
      $scope.choice.product = null;
      $scope.choice.status = null;
  };   
});
<script src="//unpkg.com/angular/angular.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

  Select a product:
  <select ng-model="choice.product" ng-options="prd for prd in productChoices">
      <option value="">Select a product</option>
  </select>
  <br/> Select a status:
  <select ng-model="choice.status" ng-options="prd for prd in statusChoices">
      <option value="">Select a status</option>
  </select>

  <hr/> selected product: {{choice.product}}
  <br/> selected status: {{choice.status}}
  <br/>
  <button type="button" ng-click="reset()">
    Reset
  </button>
</div>

答案 1 :(得分:0)

可能有很多事情...下面的代码应该有所帮助,否则您可以分享自己的位置:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.firstName = "John";
  $scope.lastName = "Doe";
  $scope.output = {
    'product': "",
    'status': ""
  }
  $scope.productChoices = ['product A', 'product B', 'product C', 'product D', 'product E'];
  $scope.statusChoices = ['active', 'pending', 'completed', 'cancelled'];
});
select {
  min-width: 100px;
}
<script src="https://code.angularjs.org/1.1.0/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

  Select a product:
  <select style="margin-left:5px;width:60px" id="product" ng-model="output.product" ng-options="prd for prd in productChoices">
  </select>
  <br/> Select a status:
  <select style="margin-left:5px;width:60px" id="status" ng-model="output.status" ng-options="prd for prd in statusChoices">
  </select>

  <hr/> selected product: {{output.product}} <br/> selected status: {{output.status}}<br/>

  <br/>
  <button type="button" ng-click="output = {'product':'', 'status': ''}"> Reset
</button>
</div>