2016-05-20 55 views
0

我希望你們能幫助我。根據條件ng-change更改ng-model字段的值

我想根據(看似)簡單的條件語句來設置我的AngularJS視圖字段中的一個的值。

我確實相信答案會如此簡單,但經過一個多小時的搜索和嘗試之後,我一直無法找到答案。

我想我可能會嘗試使用錯誤的指令(我嘗試過像ng-if和ng-change這樣的東西)。

這就是我想要達到的目標:

當我更改報告頻率爲每週(ng-if="reportSettingsData.ReportFrequencyName.ReportFrequencyId == Enum.ReportFrequency.Weekly)設置我的NG-模型場reportSettingsData.ReportFrequencyWeekdayName = "None"的價值。

而反之亦然;當我更改報告頻率爲每月(ng-if="reportSettingsData.ReportFrequencyName.ReportFrequencyId != Enum.ReportFrequency.Weekly)時,請將我的ng型號字段reportSettingsData.ReportFrequencyMonthDayName = "None"的值設置爲。

<!-- Frequency --> 
<div class="col-md-3"> 
    <label>Frequency</label> 
    <div class="input-dropdown"> 
     <cc-dropdown cc-placeholder="Report Frequency" 
         ng-model="reportSettingsData.ReportFrequencyName" 
         ng-options="reportSettingsData.SelectableReportFrequencyNames" 
         cc-fields="ReportFrequencyName" 
         ng-change="frequencyChanged()" 
         cc-key-field="ReportFrequencyId" 
         cc-allow-search="reportSettingsData.SelectableReportFrequencyNames != null && reportSettingsData.SelectableReportFrequencyNames.length > 5" 
         name="iFrequencyName"> 
     </cc-dropdown> 
    </div> 
</div> 

<!-- Week Days/Month Days --> 
<div class="col-md-3"> 
    <label>Frequency Options</label> 
    <div class="input-dropdown" ng-if="reportSettingsData.ReportFrequencyName.ReportFrequencyId != Enum.ReportFrequency.Weekly"> 
     <cc-dropdown cc-placeholder="Report Frequency Option" 
         ng-model="reportSettingsData.ReportFrequencyMonthDayName" 
         ng-options="reportSettingsData.SelectableReportFrequencyMonthDays" 
         ng-disabled="reportSettingsData.ReportFrequencyName.ReportFrequencyId != Enum.ReportFrequency.Monthly" 
         cc-fields="ReportFrequencyMonthDayName" 
         cc-key-field="ReportFrequencyMonthDayId" 
         cc-allow-search="true" 
         name="iFrequencyMonthDays"> 
     </cc-dropdown> 
    </div> 

    <div class="input-dropdown" ng-if="reportSettingsData.ReportFrequencyName.ReportFrequencyId == Enum.ReportFrequency.Weekly"> 
     <cc-dropdown cc-placeholder="Report Frequency Option" 
         ng-model="reportSettingsData.ReportFrequencyWeekdayName" 
         ng-options="reportSettingsData.SelectableReportFrequencyWeekdays" 
         cc-fields="ReportFrequencyWeekdayName" 
         cc-key-field="ReportFrequencyWeekdayId" 
         cc-allow-search="true" 
         name="iFrequencyWeekdays"> 
     </cc-dropdown> 
    </div> 
</div> 

我非常感謝你提前!

回答

1

Ng-if僞指令用於根據條件刪除或創建一個dom元素,請參閱https://docs.angularjs.org/api/ng/directive/ngIf

對於您的使用情況,它不是必需的。

綁定到ng-change事件並在函數中爲模型字段設置適當的值。

$scope.frequencyChanged = function(){ 
    if($scope.reportSettingsData.ReportFrequencyName.ReportFrequencyId == Enum.ReportFrequency.Weekly){ 
    $scope.reportSettingsData.ReportFrequencyWeekdayName = "None". 
    } 
}; 

希望這會有所幫助。

+0

我已經實現了您的建議,並且可以達到預期目的,但並不像我期望的那樣。如果你願意,請看我編輯的問題。謝謝! – onmyway