2013-05-31 31 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

感谢这让我更加了解我在做什么。 –