我在表单中使用无线电输入,我在它们上面放了相同的ng-model
。但是我无法在控制器中获取值,但是我可以获得其他ng-model
字段的值。
您可以在jsfiddle和codepen上找到我的代码(由于某些原因,这些代码都不起作用)
%form.project{'ng-submit' => "createNewProject()"}
.name
%input{'ng-model'=>'name', :type => :text, :placeholder => 'Name', :name => "name"}
.description
%textarea{'ng-model'=>'description', :placeholder => 'Description', :required=>true, :name => "description"}
.orientation
%input#portrait{'ng-model'=>'orientation', :type=>"radio", :name=>"orientation", :value=>"1", :checked=>true}
%label{:for=>"portrait"}
%input#landscape{'ng-model'=>'orientation', :type=>"radio", :name=>"orientation", :value=>"2"}
%label{:for=>"landscape"}
app.controller('theController', ['$scope', function($scope)
{
$scope.createNewProject = function()
{
var item = {
name:this.name,
description:this.description,
orientation:this.orientation
};
//item.orientation is undefined
}
}]);
答案 0 :(得分:0)
在控制器中,创建属性方向并将其设置为您希望设置无线电输入的默认值(删除无线电输入中的:checked=>true
)。
%input#portrait{'ng-model'=>'orientation', :type=>"radio", :name=>"orientation", :value=>"1"}
%label{:for=>"portrait"}
%input#landscape{'ng-model'=>'orientation', :type=>"radio", :name=>"orientation", :value=>"2"}
%label{:for=>"landscape"}
app.controller('theController', ['$scope', function($scope)
{
$scope.orientation = 1;
$scope.createNewProject = function()
{
var item = {
name:this.name,
description:this.description,
orientation:this.orientation
};
//item.orientation is undefined
}
}]);
如果您不首先创建orientation属性,则在收音机输入更改之前不会初始化它,因此您将this.orientation
未定义。
因此解决方案是在控制器中设置$scope.orientation
的值。
它将创建属性,因此您没有将其定义为未定义,并且,将无线电输入设置为默认位置,因此:checked=>true
变得无用(并且无论如何对该属性没有任何影响)