如何使用ng-init和ng-repeat

时间:2016-10-19 06:04:50

标签: javascript angularjs angularjs-ng-repeat angular-ngmodel angularjs-ng-value

我正在创建一个Web应用程序,我在其中使用dropdown和angularjs来更新我的数据库,

这是我的下拉列表的语法

<select ng-model="ucomname" ng-change="uucomname(o)">
       <option ng-repeat="o in comnamelistfun" value="{{o.comname}}">{{o.comname}}</option>
</select>

此下拉列表中的第一个值是空白但我希望我的下拉列表的第一个值是我的下拉列表的第一个值,当我使用ng-init时,我无法在ng-model中发送任何想法的值?

3 个答案:

答案 0 :(得分:1)

首先在你的控制器中,

app.controller('cardController', ['$scope',
    function($scope) {
    $scope.ucomname = $scope.comnamelistfun[0]
}])

然后选择框是,

<select ng-model="ucomname" ng-change="uucomname(o)" ng-options="o for o in comnamelistfun">
</select>

这件事适合你。

答案 1 :(得分:1)

你可以用它。     this github issue

    (function() {
  'use strict';

  angular
    .module('app', [])
    .controller('HomeCtrl', HomeCtrl);

  HomeCtrl.$inject = ['$scope'];

  function HomeCtrl($scope) {

    $scope.cities = [
      { id: 1, name: 'London' },
      { id: 2, name: 'Chicago' },
      { id: 3, name: 'Moscow' },
      { id: 4, name: 'Mumbai' },
      { id: 5, name: 'Casablanca' }
      ];

    // Pre-select city by id
    $scope.selectedCityId = 1;

    // Pre-select city by object
    $scope.selectedCity = { id: 1, name: 'Casablanca' };

  }
})();

    <!DOCTYPE html>
<html ng-app="app">

<head>
  <link rel="stylesheet" href="style.css" />
</head>

<body ng-controller="HomeCtrl">
  <h3>Data List</h3>

  <table>
    <tbody>
      <tr ng-repeat="city in cities">
        <td>{{city.id}}</td>
        <td>{{city.name}}</td>
      </tr>
    </tbody>
  </table>

  <h3>Selected City (by Id)</h3>
  selectedCityId: <strong>{{selectedCityId}}</strong>
  <br/>
  <br/>
  <label>Select City
    <select ng-model="selectedCityId" ng-options="city.id as city.name for city in cities">
      <option value="">-- Select City --</option>
    </select>
  </label>

  <hr/>

  <h3>Selected City (by object)</h3>
  selectedCity: <strong>{{selectedCity}}</strong>
  <br/>
  <br/>
  <label>Select City
    <select ng-model="selectedCity" ng-options="city as city.name for city in cities track by city.id">
      <option value="">-- Select City --</option>
    </select>
  </label>

  <hr/>

  <!-- Scripts -->
  <script data-require="angular.js@1.5.6" data-semver="1.5.6" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
  <script src="HomeCtrl.js"></script>

</body>
</html>

答案 2 :(得分:0)

试试这段代码。

<select ng-model="ucomname" ng-options= "o.comname for o in comnamelistfun track by o.comname">
</select>

并在您的控制器中。放这个。

$scope.ucomname = $scope.comnamelistfun[0]; //This will select the first element.

我希望它应该有效:)