ngChange处理对象数组

时间:2015-08-28 07:23:57

标签: javascript angularjs

我正在努力与angularJS一起使用ngRepeat进行选择。 我选择这种方式是因为我收到的数据是:

{ 
"id": "day-pro", 
"data": [ 
        { "countries": [ "FRANCE", "SPAIN","GERMANY"] }, 
        { "country": "FRANCE", 
         "achieved": [ 4, 12, 23, 24, 24, 27, 35, 41 ], 
         "target": [ 56, 72, 79, 89, 92, 99, 100, 100 ] 
         } ]}

我使用的指令模板是:

<div ng-controller="hBarController">
    <select id="sel-day-pro" class="frm-drop" data-ng-change="selectCountry($event)">
        <option data-ng-repeat="opt in Countries">{{opt}}</option>
    </select>
<div class="daily-progress-chart">Select a country</div>

daily-progress-chart div中,它将是选择时绘制的图表。

我遇到的错误是该指令需要ngModel,但是将其插入require:&#34; ^ ngModel&#34;不解决它。

Angular指令:

App.directive('myFrmContent', function () {
    return {
        restrict: "E",
        require: '^ngModel',
        template: "<div ng-include=\"getTemplateUrl()\"></div>",
        controller: function ($scope) {
            $scope.getTemplateUrl = function () {
                var btnID = '';
                if ($scope && $scope.widget && $scope.widget.id) {
                    btnID = $scope.widget.id;
                }
                return "htmlTemplates/" + btnID + ".html" || '';
            };
        }
    };
});   

1 个答案:

答案 0 :(得分:1)

你实际上错过了错误:

需要ng-model的指令是ng-change

注意:在选择中使用ng-model(例如ng-model="selectedCountry")会自动将var(selectedCountry)更新为实际的value(或ng-value )选项。

ng-change是一个指令,可以对ng-model变量进行一些操作。这就是它需要ng-model指令

的原因

你应该最终得到这样的东西:

<div ng-controller="hBarController">
    <select id="sel-day-pro" ng-model="selectedCountry" class="frm-drop" data-ng-change="handleChangeSelectedCountry()">
        <option ng-value="opt" data-ng-repeat="opt in Countries">{{opt}}</option>
    </select>
<div class="daily-progress-chart">Select a country</div>

在你的控制器中:

$scope.handleChangeSelectedCountry = function(){
   //Do something you want to do on each change of the selectedCountry value
   //Do NOT manually set the value of selectedCountry
}

希望它有所帮助。

编辑:这是plunker和更清洁的解决方案

我想出了这个:

<select data-ng-model="selectedCountry" 
        data-ng-options="country for country in data.data[0].countries"
        id="sel-day-pro" class="frm-drop">
</select>
<div>Currently selected {{selectedCountry}}</div>

控制器中没有JS。

如果您需要处理其他内容而不是设置var(selectedCountry),请在答案中按照我的建议高手使用ng-change来处理您所需的行为。

PS:请注意,您的实际JSON强迫我执行此操作data.data[0].countries而不是此data.data.countries

相关问题