2013-05-31 34 views
3

我將用戶輸入傳遞給控制器​​函數,但空字符串不聲明對象屬性。ng-model未定義爲空字符串?

<form> 
    <input type="text" ng-model="data.location" /> 
    <input type="text" ng-model="data.radius" /> 
    <button type="button" ng-click="getSearch(data)">Search</button> 
</form> 

$scope.getSearch = function(data) { 
    console.log(data); 
    //undefined 
    //...but what if I want {location:'', radius:''} 
}; 

有沒有辦法強制空中傳遞空字符串時創建的對象屬性?

回答

4

您應該能夠將控制器中的data.location和data.radius初始化爲'',至少它們不是未定義的。

+0

訪問當然,但這是唯一的方法嗎?沒有辦法強制它在飛行中? –

+0

@DanKanze沒有其他對象將被初始化,只有當你編輯文本框 –

+0

ng-init = {data:{location:'',radius:''}「會做的伎倆,但它在控制器 – Mephiztopheles

3

您應該以$scope.data的身份訪問它,而不僅僅是data

此外,您不需要將它作爲參數傳遞給您的getSearch()models綁定到$scope,應該通過$scope

+0

感謝這讓我更加了解我在做什麼。 –