【问题标题】:Select not bind with model选择不与模型绑定
【发布时间】:2015-06-29 06:29:44
【问题描述】:

我在使用 select 和您的模型时遇到问题。在此示例中,usaStates 是存储在根范围内的对象数组。

<label>State:</label>
<select name="state" ng-model="selectedState" ng-options="state.name for state in usaStates" required ng-change="getCities()">
    <option>Select a state</option>
</select>

所以,在我的控制器中,我有:

$scope.selectedState = null;
$scope.getCities = function()
{
   console.log($scope.selectedState);
   var stateCode = $scope.selectedState.id;
   MainService.getCities(stateCode)
   .then(function(httpData){
      $scope.cities = httpData.data;
   })
   .catch(function(error){
      console.log(error);
   });
};

当一个状态被选中时,getCities 函数被触发,但$scope.selectedState 为空。我在另一个视图中有这段代码并且工作正常。为什么这里没有?有什么想法吗?

更新 我的状态来源是:

[{id: "AL", name: "Alabama"}, {id: "AK", name: "Alaska"}, {id: "AZ", name: "Arizona"},…]

【问题讨论】:

  • usaStates 对象长什么样子?
  • 另外,你能分享一个 jsfiddle/plnkr 吗?
  • 您可以尝试将 ng-model 更改为对象吗,ng-model=selectedState.Name

标签: angularjs combobox angular-ngmodel


【解决方案1】:

可能模型值没有得到知识,ng-change 被提前触发。

您可以将其作为参数传递。

<select name="state" ng-model="selectedState" ng-options="state.name for state in usaStates" required ng-change="getCities(selectedState)">
    <option>Select a state</option>
</select>

在控制器中。

$scope.selectedState = null;
$scope.getCities = function(selectedState)
{
   console.log(selectedState);
   var stateCode = selectedState.id;
   MainService.getCities(stateCode)
   .then(function(httpData){
      $scope.cities = httpData.data;
   })
   .catch(function(error){
      console.log(error);
   });
};

【讨论】:

  • 谢谢,但结果是一样的-
【解决方案2】:

尝试将selectedState 传递给getCities(selectedState) 函数。

例如

HTML

<select name="state"
        ng-model="selectedState" 
        ng-options="state.name for state in usaStates" 
        ng-change="getCities(selectedState)"
        required="required">
    <option>Select a state</option>
</select>

JS

$scope.selectedState = null;
$scope.getCities = function(selectedState) {
    $scope.selectedState = selectedState;
    console.log($scope.selectedState);
    var stateCode = $scope.selectedState.id;
    MainService.getCities(stateCode)
            .then(function(httpData) {
                $scope.cities = httpData.data;
            })
            .catch(function(error) {
                console.log(error);
            });
};

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2020-12-07
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    相关资源
    最近更新 更多