【问题标题】:radio inputs not working with angular无线电输入不适用于角度
【发布时间】:2013-07-25 23:28:06
【问题描述】:

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

您可以在 jsfiddle 和 codepen 上找到我的代码(由于某些原因,它们都不起作用)

这里是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
    }

}]);

【问题讨论】:

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


    【解决方案1】:

    解决方案

    在控制器中,创建属性方向并将其设置为您希望设置无线电输入的默认值(删除无线电输入中的: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 undefined。

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

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

    【讨论】:

      猜你喜欢
      • 2015-10-03
      • 1970-01-01
      • 2021-01-10
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      • 2018-11-20
      • 2015-06-12
      相关资源
      最近更新 更多