【问题标题】:Angular - Ng-change return always the same valueAngular - Ng-change 总是返回相同的值
【发布时间】:2014-11-21 07:22:47
【问题描述】:

我想问一下,如何从单选列表中获取选定的值?

我尝试了 ng-change 并观察范围,但我总是只得到在应用程序初始化期间设置到模型中的第一个值。

这是我的代码示例:

单选按钮组:

<div class="list" ng-contoller="SettingsCtrl">
        <ion-radio ng-model="choice" ng-value="'dials'">Dials</ion-radio>
        <ion-radio ng-model="choice" ng-value="'conversations'">Conversations</ion-radio>
        <ion-radio ng-model="choice" ng-value="'appoitnments'">Appointments</ion-radio>
        <ion-radio ng-model="choice" ng-value="'orders'">Orders</ion-radio>
      </div>

JS:

// Default choice scope
$scope.choice;

$scope.$watch('choice', function(value) {
            // Here i get always the same value
            console.log("Selected goalType, text: " +value);
});

如何获取选定值并将此值设置到范围内?

感谢您的帮助。

【问题讨论】:

    标签: javascript angularjs radio-group


    【解决方案1】:

    不使用离子框架和输入单选按钮,它可以工作。 你刚刚在这条线上犯了一个错误&lt;div class="list" ng-contoller="SettingsCtrl"&gt;。 您忘记了控制器中的 r。

    这里是工作代码: HTML

    <!DOCTYPE html>
    <html ng-app="app">
    
      <head>
        <script data-require="angular.js@1.2.25" data-semver="1.2.25" src="https://code.angularjs.org/1.2.25/angular.js"></script>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js"></script>
      </head>
    
      <body >
        <div class="list" ng-controller="SettingsCtrl">
            <input type="radio" ng-model="choice" ng-value="'dials'">Dials
            <input type="radio" ng-model="choice" ng-value="'conversations'">Conversations
            <input type="radio" ng-model="choice" ng-value="'appoitnments'">Appointments
            <input type="radio" ng-model="choice" ng-value="'orders'">Orders
          </div>
      </body>
    
    </html>
    

    还有 JavaScript :

    var app = angular.module('app', []);
    
    app.controller('SettingsCtrl', function($scope){
      $scope.choice;
      console.log('ctrl');
      $scope.$watch('choice', function(value) {
                  // Here i get always the same value
                  console.log("Selected goalType, text: " +value);
      });
    });
    

    你可以看到它在这里工作: http://plnkr.co/edit/TRJKW7eOlBek6TditM1B?p=preview

    编辑 我已经用离子框架对其进行了测试。它也在工作。所以这只是 r 的问题。

    【讨论】:

      【解决方案2】:

      我为你制作了this fiddle。当您选择radio 时,$scope.currentSelection 会发生变化,这样您就可以知道哪个是当前选定的目标。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-22
        • 2019-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多