0

我在一个表单中使用无线电输入,我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
    }

}]);
4

1 回答 1

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

控制器

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
    }

}]);

过程如下:

如果您不先创建方向属性,则在无线电输入更改之前它不会被初始化,因此您将有this.orientation未定义的。

所以解决方法是$scope.orientation在控制器中设置 的值。

它将创建属性,因此您没有未定义它,并且,将无线电输入设置为默认位置,因此:checked=>true变得无用(并且无论如何对属性没有任何影响)

于 2013-07-25T15:28:06.663 回答