2017-03-24 59 views
0

我有一個字符串作爲我的控制器中的函數的返回值。像這樣:如何將返回的字符串分配給Angular Conroller中的對象屬性?

 function concatDaysOfWeek() { 

     var DaysString = ""; 

     if (vm.sunday) DaysString = DaysString + '1'; 
     if (vm.monday) DaysString = DaysString + '2'; 
     if (vm.tuesday) DaysString = DaysString + '3'; 
     if (vm.wednesday) DaysString = DaysString + '4'; 
     if (vm.thursday) DaysString = DaysString + '5'; 
     if (vm.friday) DaysString = DaysString + '6'; 
     if (vm.saturday) DaysString = DaysString + '7'; 

     return DaysString; 

    } 

現在我有一個對象需要填充屬性。

 vm.schedule = {}; 

在我的HTML中,我創建了一堆綁定到這個對象的ng模型。 但我不知道如何將我得到的字符串作爲返回值綁定到我的對象中的屬性。

我想是這樣的:

RecurrenceDaysOfWeek: DaysString 

但它不工作。不在對象內部,也不在控制器中的其他位置。

請幫忙。謝謝

+0

'vm.schedule = {XYZ:concatDaysOfWeek()};後我' – Satpal

+0

是否我看到這個{「RecurrenceDaysOfWeek」:「」}。即使我選擇了這些日子,也是一個空字符串。所以這並沒有解決它。我希望看到日子在我選擇和取消選擇時發生變化。 – froglim

回答

0

爲什麼不把它設置在你的方法?

function concatDaysOfWeek() { 

    var DaysString = ""; 
    if (vm.sunday) DaysString = DaysString + '1'; 
    if (vm.monday) DaysString = DaysString + '2'; 
    if (vm.tuesday) DaysString = DaysString + '3'; 
    if (vm.wednesday) DaysString = DaysString + '4'; 
    if (vm.thursday) DaysString = DaysString + '5'; 
    if (vm.friday) DaysString = DaysString + '6'; 
    if (vm.saturday) DaysString = DaysString + '7'; 

    vm.schedule.myVariable = DaysString; 
} 
+0

謝謝!!這工作。我只是在賦值之前返回了DaysString。這就是我得到錯誤的原因。 – froglim

+0

如果您發現此答案有幫助,您可以請upvote /選擇它作爲選擇的答案,以便其他人查看問題知道嗎? :) –

0

使用ng-init調用的函數和將值分配給ng-model

<input ng-model="vm.schedule.RecurrenceDaysOfWeek" ng-init="vm.schedule.RecurrenceDaysOfWeek = vm.concatDaysOfWeek()"/> 

angular.module("app",[]) 
 
.controller("ctrl",function($scope){ 
 
    var vm = this; 
 
    vm.concatDaysOfWeek = concatDaysOfWeek; 
 
    vm.schedule = {} 
 
    vm.sunday = "1"; 
 
    function concatDaysOfWeek() { 
 

 
     var DaysString = ""; 
 

 
     if (vm.sunday) DaysString = DaysString + '1'; 
 
     if (vm.monday) DaysString = DaysString + '2'; 
 
     if (vm.tuesday) DaysString = DaysString + '3'; 
 
     if (vm.wednesday) DaysString = DaysString + '4'; 
 
     if (vm.thursday) DaysString = DaysString + '5'; 
 
     if (vm.friday) DaysString = DaysString + '6'; 
 
     if (vm.saturday) DaysString = DaysString + '7'; 
 

 
     return DaysString; 
 

 
    } 
 

 
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="ctrl as vm"> 
 
<input ng-model="vm.schedule.RecurrenceDaysOfWeek" ng-init="vm.schedule.RecurrenceDaysOfWeek = vm.concatDaysOfWeek()"/> 
 
</div>

相關問題