2015-08-28 85 views
0

我與angularJS掙扎的陣列工作使用ngRepeat做出選擇與選擇。 我選擇了這條路,因爲我得到的數據是這樣的:ngChange對象上

{ 
"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但將其插入要求:「^ ngModel」不會解決這個問題。

角指令這裏:

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

我不明白爲什麼這個指令需要'ngModel'。 Waht錯誤你會得到嗎? – k102

+1

指令被命名爲'myFrmContent',但'my-frm-content'不在html中? – ShaharZ

+0

你在哪裏使用該指令? HTML中沒有任何''元素。這應該是密切的,因爲真的不清楚。 –

回答

1

你居然missunderstood錯誤:

需要的ng-modelng-change的指令。

注意:在選擇使用ng-modelng-model="selectedCountry"的爲例)將自動更新變種(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代替本​​