简体   繁体   English

<select> AngularJS和ng-selected

[英]<select> AngularJS and ng-selected

I have HTML code like this: 我有这样的HTML代码:

 <div ng-controller="SimpleController">
    <select ng-model="item.category" ng-options="category as category.name for category in categories">
    </select> 
    <br />Item: {{item | json}}
 </div>

And js: 和js:

var app = angular.module("partnerModule", []);
app.controller("SimpleController", function($scope) {
    $scope.item = {category: {name:'Cat1', id: '1'}, name : "Item name"};
    $scope.categories = [{name:'Cat1', id: '1'}, {name: 'Cat2', id: '2'}, {name:'Cat3', id: '3'}];
});

I want to have already set option for "Cat1" when form is displayed. 我想在显示表单时已经为“ Cat1”设置选项。 I tried to add something like this: 我试图添加如下内容:

ng-selected="item.category.id == category.id"

For both <select> and <option> tags it didn't work 对于<select><option>标记均无效

This will work: html 这将起作用:html

 <div ng-controller="SimpleController">
    <select ng-model="item.category" ng-options="category as category.name for category in categories track by category.id">
    </select> 
    <br />Item: {{item | json}}
 </div>

In JS 在JS中

var app = angular.module("partnerModule", []);
app.controller("SimpleController", function($scope) {
    $scope.item = {category: {name:'Cat1', id: '1'}, name : "Item name"};
    $scope.categories = [{name:'Cat1', id: '1'}, {name: 'Cat2', id: '2'}, {name:'Cat3', id: '3'}];
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM