【问题标题】:NG-Model and Array - How it works?NG-Model 和 Array - 它是如何工作的?
【发布时间】:2015-05-05 07:59:09
【问题描述】:

我应该有以下代码:

.JS

angularcomponents.controller('CountryCntrl', ['$scope', function($scope) { 
    $scope.countries = {
                    'India': {
                        'Maharashtra': ['Pune', 'Mumbai', 'Nagpur', 'Akola'],
                        'Madhya Pradesh': ['Indore', 'Bhopal', 'Jabalpur'],
                        'Rajasthan': ['Jaipur', 'Ajmer', 'Jodhpur']
                    },
                    'USA': {
                        'Alabama': ['Montgomery', 'Birmingham'],
                        'California': ['Sacramento', 'Fremont'],
                        'Illinois': ['Springfield', 'Chicago']
                    },
                    'Australia': {
                        'New South Wales': ['Sydney'],
                        'Victoria': ['Melbourne']
                    }
                };
}]);

和html:

<div ng-controller="CountryCntrl">
    <div class="col-sm-4">
        <select id="country" ng-model="states" ng-options="country for (country, states) in countries">
            <option value=''>
                Select
            </option>
        </select>
        <br>
        <small><em>Country</em></small>
    </div>
    <div class="col-sm-4">
        <select id="state" ng-disabled="!states" ng-model="cities" ng-options="state for (state,city) in states">
            <option value=''>
                Select
            </option>
        </select>
        <br>
        <small><em>States</em></small>
    </div>
    <div class="col-sm-4">
        <select id="city" ng-disabled="!cities || !states" ng-model="city">
            <option value=''>
                Select
            </option> 
            <option ng-repeat="city in cities" value='[[city]]'>
                [[city]]
            </option>
        </select>  
        <br>
        <small><em>City</em></small>      
    </div>
</div>

我不明白它如何为城市、国家和州绑定正确的价值观。在我的 $scope 中没有任何标签可以识别它。

是否取决于数组的格式?

【问题讨论】:

  • 你能给我一个提琴手演示吗?
  • 也许问题有点不清楚,你是在问为什么选择框绑定到正确的城市、州和国家?您的对象是使用关系创建的这一事实意味着它们是?

标签: angularjs angularjs-directive angular-ngmodel


【解决方案1】:

您不需要在 javascript 中定义变量(尽管您可能更愿意) - 当您声明 ng-model 时,会在 $scope 上为您创建一个变量。因此,您的国家/地区选择绑定到一个模型州,该模型最初没有任何价值。

因为你做了country for (country, states),所以那个select的标签是数组键,也就是国家名。该值绑定到数组值。因此,当您选择一个国家/地区时,$scope.states 会填充与该国家/地区对应的完整数组。

所以现在$scope.states 中有一个数组,它允许ng-options="state for (state,city) in states" 构建一个选择器,等等。

您可以通过显示模型变量的内容来查看它的发生情况。这是一个小提琴来表明:https://jsfiddle.net/wbpm8bc7/

如您所见,最初它什么也不显示,因为这些变量是空的。但是当您进行选择时,它们会被数组填充。

【讨论】:

  • 非常感谢,我可以想象。因此,如果我更改对象的结构,则选择中的一切都会有所不同。没事吧?
  • 没错,您的选择将对应于您设置的数组或子数组。
猜你喜欢
  • 2017-01-18
  • 2017-11-26
  • 2015-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-25
  • 2019-06-24
  • 2013-07-28
相关资源
最近更新 更多