无线电输入无法使用角度

时间:2013-07-25 14:33:28

标签: ruby-on-rails angularjs radio-button

我在表单中使用无线电输入,我在它们上面放了相同的ng-model。但是我无法在控制器中获取值,但是我可以获得其他ng-model字段的值。

您可以在jsfiddlecodepen上找到我的代码(由于某些原因,这些代码都不起作用)

这是haml表单

%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
    }

}]);

1 个答案:

答案 0 :(得分:0)

解决方案

在控制器中,创建属性方向并将其设置为您希望设置无线电输入的默认值(删除无线电输入中的:checked=>true)。

HAML

%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"}

CONTROLLER

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变得无用(并且无论如何对该属性没有任何影响)