Angular JS - 将选定的文本作为ng模型(不含ng-options)

时间:2014-12-11 15:33:22

标签: javascript angularjs angular-ngmodel angularjs-ng-options angularjs-ng-model

在我的代码后面,我按如下方式填充DropDownList(使用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")

然后在客户端,我有一个select标签,它填充了服务器端的选项,如下所示:

<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的值时,我都会CountryNameINUSML等等。此外,我无法做到编辑选项的值,因为它们在服务器端代码中使用。

我希望CountryName代替IndiaUnited StatesMalaysia!我该怎么办?

2 个答案:

答案 0 :(得分:3)

服务器向您发送了哪些数据?

这是一些像这样的对象吗?

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

如果是,那么你可以轻松使用ng-options(即使你没有,它只是更好)。

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

或者,如果您实际上正在使用服务器端生成的html页面而没有javascript对象,那么它有点小问题: (假设您可以使用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();
};

答案 1 :(得分:2)

在PHP BackEnd数组中向Json Out:&lt; ? php echo json_encode($ arrayDemo); ? &GT;

// Init Load
$(function () {
    'use strict';
    angular
        .module('ngjsapp', [])
        .controller('FormCtrl', ['$scope', function ($scope) {

            var myArraySelect = <?php echo json_encode($arrayDemo); ?>

            $scope.changeSenasaProvinciasId = function (id) {
                console.log(myArraySelect[id]);
            }

        }]);
});

仅限HTML Stact + jQuery

// Option 1
$(function () {
    'use strict';
    angular
        .module('ngjsapp', [])
        .controller('FormCtrl', ['$scope', function ($scope) {

            $scope.changeSenasaProvinciasId = function () {
                console.log($("#mySelectID option:selected").text());
            }

        }]);
});

仅限HTML Stact + jQuery BEST

// Option 2
$(function () {
    'use strict';
    angular
        .module('ngjsapp', [])
        .controller('FormCtrl', ['$scope', function ($scope) {

            var myArraySelect = $('#mySelectID option').each( function() { 
                    myArraySelect.push({$(this).val() : $(this).text() });
                });

            $scope.changeSenasaProvinciasId = function (id) {
                console.log(myArraySelect[id]);
            }

        }]);
});