如何以角度js编程选择?

时间:2018-05-15 06:53:02

标签: javascript html angularjs

我想显示select的当前值。但它什么都没显示。我该怎么做?这是我的测试代码:

<div class="input-field col s12" ng-init="test=2">
        <label for="item_code" class="active">Category</label>
          <select 
            ng-model="test"
            ng-options="c.name for c in categories track by c.id"
          >
          </select>
          <p>This is the value {{test}}</p>
      </div>

2 个答案:

答案 0 :(得分:2)

由于您将模型指定为testng-model="test"),因此您需要使用相同的值来显示该值。替换这个:

<p>This is the value {{testSelect}}</p>

用这个:

<p>This is the value {{test}}</p>

修改1:

正如评论中提到的OP,他正在使用ng-init="test=2"初始化模型test。此代码存在的问题是,在ng-options中,您需要使用value数据设置option nameng-options="c.name for c in categories track by c.id" 。见这句话:

c.name

由于2在任何地方都不匹配c.name,因此下拉列表不会选择任何元素。将c.id更改为ng-options="c.id as c.name for c in categories track by c.id" ,它将开始工作:

import { environment } from '../../../environments/environment';
// use path to your environments file.

private apiEndPoint: string;

constructor() {
    this.apiEndPoint = environment.apiUrl;
}

答案 1 :(得分:2)

试试这个: -

$socpe.test = {"id":1,name:"category 1"}

要设置选择标记的默认值,请使用: -

{{1}}