0

我有与这里提到的完全相同的问题:如何在 Angular.js 选择框中有一个默认选项

但是,没有一个答案可以解决我的问题,我试图让第一个类别显示在选择中:

在此处输入图像描述

<p>Choose a tag category:</p>
<div class="select-style">
    <select ng-model="modal.addedTag" ng-init="modal.addedTag = modal.categories[0].name" ng-options="category.name for category in modal.categories">
        <!-- <option value="brand" selected>Brand</option> 
        <option value="client">Client</option>
        <option value="company-name">Company Name</option>
        <option value="government">Government</option>
        <option value="events">Events</option>
        <option value="industry">Industry</option>
        <option value="products">Products</option>
        <option value="news">News</option> -->
    </select>
</div>

我的控制器中的模型:

var vm = this;
vm.categories = [
    { name: 'brand' },
    { name: 'client' },
    { name: 'competitor-name' },
    { name: 'company-name' },
    { name: 'government' },
    { name: 'events' },
    { name: 'industry' },
    { name: 'people' },
    { name: 'philanthropic' },
    { name: 'products' },
    { name: 'product-category' },
    { name: 'product-feature' },
    { name: 'place' },
    { name: 'problem' },
    { name: 'news' },
    { name: 'related-company-name' },
    { name: 'trend' }
];
4

2 回答 2

2

可以尝试初始化vm.addedTagfromcontroller而不是 inDOM

vm.addedTag = vm.categories[0].name; // after your categories array 

而在html中只使用ng-model不需要使用ng-init和使用category.name as category.name

<select ng-model="modal.addedTag" ng-options="category.name as category.name for category in modal.categories"></select>
于 2016-04-01T19:36:08.543 回答
1

在控制器中试试这个。

如果您使用ng-options="category.name for category in modal.categories" 选择标签,则 vm.addedTag = vm.categories[0];在控制器中初始化。并ng-options="category.name as category.name for category in modal.categories"在选择标签中使用,然后像这样初始化 vm.addedTag 模型vm.addedTag = vm.categories[0].name;

var myapp = angular.module('app', []);
myapp.controller('Main', function ($scope) {
 var vm = this;
vm.categories = [
    { name: 'brand' },
    { name: 'client' },
    { name: 'competitor-name' },
    { name: 'company-name' },
    { name: 'government' },
    { name: 'events' },
    { name: 'industry' },
    { name: 'people' },
    { name: 'philanthropic' },
    { name: 'products' },
    { name: 'product-category' },
    { name: 'product-feature' },
    { name: 'place' },
    { name: 'problem' },
    { name: 'news' },
    { name: 'related-company-name' },
    { name: 'trend' }
];
  vm.addedTag = vm.categories[0];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app = "app">
  <div ng-controller="Main as modal">

<div class="select-style">
    <select ng-model="modal.addedTag"  ng-options="category.name for category in modal.categories">
       
    </select>
</div>
   </div>
</div>

于 2016-04-01T19:36:41.950 回答