javascript - ngChange 处理对象数组

标签 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: "^ngModel"无法解决该问题。

此处的 Angular Directive(指令):

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" || '';
            };
        }
    };
});   

最佳答案

您实际上误解了错误:

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

注意:在选择上使用 ng-model (例如 ng-model="selectedCountry")将自动更新 var (selectedCountry) >) 到选项的实际(或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>

在你的 Controller 中:

$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>

Controller 中没有 JS。

如果您需要处理除设置 var (selectedCountry) 之外的其他内容,请按照我在答案中的建议进行操作,并使用 ng-change 来处理您所需的行为。

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

关于javascript - ngChange 处理对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32265486/

相关文章:

angularjs - 如何根据每条记录的数据动态显示 Angular.js 中的货币?

javascript - ionic 按钮点击时持续时间长

javascript - 独立运行两个函数

javascript - Svelte - 如何使数据不 react ?

javascript - JQuery Mobile,加载然后更改可能吗?

javascript - 删除固定列 DataTables 下的水平滚动条

javascript - 检查动态文本字段Angularjs的输入字段是否为空

javascript - 当多次调用时,Angular 服务会覆盖自身

javascript - Angularjs 不会触发由 addEventListener 处理的事件

javascript - 将 Javascript 添加到向下箭头按钮以打开和关闭子菜单