使用 bootstrap ui 单选按钮时在控制器中获取 ng-model 值

Get ng-model value in controller when using bootstrap ui radio button

我似乎无法将单选按钮的值返回到控制器中...

HTML

<div class="btn-group-wrap">
  <div class="btn-group listBtn text-center">
    <label uib-btn-radio="0" ng-change="newDataset()" ng-model="changeDataset" class="btn btn-default">0</label>
    <label uib-btn-radio="1" ng-change="newDataset()" ng-model="changeDataset" class="btn btn-default">1</label>
    <label uib-btn-radio="undefined" ng-change="newDataset()" ng-model="changeDataset" class="btn btn-default">undefined</label>
  </div>
</div>
<p>filter {{changeDataset}}</p> //i see the change here!!

控制器

$scope.changeDataset = undefined


$scope.newDataset = function () {
  console.log('new dataset function called');
  console.log('the dataset= '+$scope.changeDataset) //but it just returns undefined here!!!
  console.log('the vacated= '+$scope.filter.vacated)
};

它识别出函数是运行,但它总是只记录undefined

您的代码有效,undefined 出现在控制台中,因为您尝试记录 $scope.filter.vacated,它被设置为 undefined

这是您的代码工作的片段演示:

angular.module('ui.bootstrap.demo', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('ButtonsCtrl', function ($scope) {
  $scope.filter = {
    vacated: undefined
  };
  
  $scope.newDataset = function () {
    console.log('new dataset function called');
    console.log('the dataset= ' + $scope.changeDataset);
    console.log('the vacated= ' + $scope.filter.vacated);
  };
});
<html ng-app="ui.bootstrap.demo">
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
    <script src="example.js"></script>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  </head>

<div ng-controller="ButtonsCtrl">
    <pre>{{changeDataset}}</pre>
    <div class="btn-group">
        <label uib-btn-radio="0" ng-change="newDataset()" ng-model="changeDataset" class="btn btn-default">0</label>
        <label uib-btn-radio="1" ng-change="newDataset()" ng-model="changeDataset" class="btn btn-default">1</label>
        <label uib-btn-radio="undefined" ng-change="newDataset()" ng-model="changeDataset" class="btn btn-default">undefined</label>
    </div>
</div>
</html>

我通过将 ng-model="changeDataset" 更改为 ng-model="$parent.changeDataset"

来解决这个问题

$parent - 映射到包含当前作用域的作用域