【问题标题】:AngularJS fill $scope.selected with object from <select>AngularJS 用 <select> 中的对象填充 $scope.selected
【发布时间】:2016-11-21 14:58:36
【问题描述】:

我在用正确的数据填充范围并保持正确的属性时遇到问题。

我有一个小的 PHP 脚本,它以 json 数组的形式返回一个 id、一个名称和一个时间。

 {
  "times": [
    {
      "id": "myID",
      "name": "myName",
      "time": "40:00:00"
    },
    ...(10 more objects)
}

我想创建一个下拉元素,名称为名称,id 为值。我在ng-repeat 上做了这个,效果很好。

<select name="StPl_Code" class="form-control" id="field-stpl-name" ng-model="selected">
    <option ng-repeat="i in times"  value="{{i.id}}">{{i.name}}</option>
</select>

我的问题是,我想将选定的 i 保存在 $scope.selected 中,以便将其时间值用于其他输入字段,而不会丢失 value 属性中的值

这是我的角度代码

  app.controller('auftraegeCrtl', function($scope, $http){
      $scope.selected = '';
      $http.get('index.php?page=times&json=true').success(function(data, status, headers, config){
        $scope.times = data.times;
      }).error(function(data, status, headers, config){
      });
  });

【问题讨论】:

标签: javascript angularjs json angularjs-scope


【解决方案1】:

你会想要使用 ng-options 指令,像这样:

<select name="StPl_Code" class="form-control" id="field-stpl-name" ng-model="selected" ng-options="i.id as i.name for i in times"></select>

你可以看到它在工作here

【讨论】:

  • 我刚找到它
【解决方案2】:

试试这个:

 $scope.selected = {};

而不是:

 $scope.selected = '';

【讨论】:

    【解决方案3】:

    改用“Ng-options”。

    <select ng-options="i as i.name for i in times track by item.id" ng-model="selected"></select>
    

    这会将 $scope.selected 设置为所选对象

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多