Angular JS - 将所选文本作为 ng 模型(不带 ng 选项) [英] Angular JS - get selected text as ng model (without ng-options)

查看:15
本文介绍了Angular JS - 将所选文本作为 ng 模型(不带 ng 选项)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我后面的代码中,我填写了一个 DropDownList 如下(使用 VB)

In my code behind, I fill up a DropDownList as follows (using VB)

ddlCountries.DataSource = dt ' dt is DataTable with columns "CountryCode" and "CountryName"
ddlCountries.DataTextField = "CountryName"
ddlCountries.DataValueField = "CountryCode"
ddlCountries.DataBind()
ddlCountries.Attributes.Add("ng-model", "CountryName")

然后是客户端,我有一个选择标签,其中填充了来自服务器端的选项,如下所示:

Then client side, I have a select tag, which is filled with options from server side as below:

<select ng-model="CountryName">
    <option value="IN">India</option>
    <option value="US">United States</option>
    <option value="ML">Malaysia</option>
    <!-- and other 200+ records -->
</select>

我不能在这里使用 ng-options!现在,每当我从 select 更改值时,我都会将 CountryName 设为 INUSML 等.此外,我无法编辑选项的值,因为它们用于服务器端代码.

I can't use ng-options here! Now, whenever I change the value from select, I get CountryName as IN, US, ML etc.. Moreover, I can't edit values of options because they're used in server side code.

这里我想将 CountryName 改为 IndiaUnited StatesMalaysia!我能做什么?

Here I want CountryName as India, United States or Malaysia instead! What can I do?

推荐答案

服务器向你发送什么数据?

What data is the server sending you?

是这样的对象数组吗?

var countries = [ 
    { name: 'India', code: 'IN'},
    { name: 'United States', code: 'US'},
    { name: 'Malaysia', code: 'ML'}
];

如果是,那么您可以轻松使用 ng-options(即使您不必这样做,它也更好).

If yes, then you can easily use ng-options (even though you dont have to, its just better).

<select ng-model="CountryName"
    ng-options="c.code as c.name for c in countries">
</select>

或者,如果您实际上正在使用服务器端生成的 html 页面并且没有 javascript 对象,那么它有点诡异:(假设您可以使用 JQuery):

Or in the case that you actually are working with server side generated html page and no javascript objects, then its a little bit tricker: (Supposing you can use JQuery):

查看:

<select id="countryNameSelect" ng-change="setCountryName()">
    <option value="IN">India</option>
    <option value="US">United States</option>
    <option value="ML">Malaysia</option>
    <!-- and other 200+ records -->
</select>

控制器:

$scope.countryName = '';
$scope.setCountryName = function() {
  $scope.countryName = $("#countryNameSelect option:selected").html();
};

这篇关于Angular JS - 将所选文本作为 ng 模型(不带 ng 选项)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆