如何在角度

时间:2017-02-13 16:57:05

标签: javascript html css angularjs

我有下拉列表,其中包含城市列表(默认选择是 - 选择城市 - )。当用户选择城市时,该城市会被添加到某个div中。一旦添加,它应设置为默认值,即 - 选择城市 - 。

有没有办法实现这个目标?没有Page reload?

2 个答案:

答案 0 :(得分:0)

如果我没记错,你要做的就是将选择输入的模型分配给其他模型,然后将初始模型重置为默认值null

这可以通过使用ng-change指令的函数来完成。

类似的东西:

$scope.select = function() {
    $scope.selectedCity = $scope.city;
    $scope.city = null;
  }

然后在视图中:

<select ng-change="select()" ng-model="city" ng-options="option for option in options">
      <option value="">Select City</option>
    </select>

这是适合您的fiddle

答案 1 :(得分:0)

试试这个:

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl',function($scope) {
    $scope.cities = [
     {"id":1,"name":"Delhi"},
     {"id":2,"name":"Hyderabad"},
     {"id":3,"name":"Pune"}
    ];
    
    $scope.selectedCities = [];
    $scope.setCity = function(city) {
      $scope.selectedCity = "";
      $scope.selectedCities.push(city);
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <select ng-model="selectedCity" ng-options="option.name as option.name for option in cities" ng-change="setCity(selectedCity)">
    <option value="">--Select City--</option>
  </select>
  <div ng-repeat="cityName in selectedCities">
   {{cityName}}
  </div>
</div>