0

我正在尝试为带有值的无线电输入创建指令。这些值将从指令传递。当单选按钮更改时,我还想更新控制器中的值。这是我想出的...

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.selected = 1;
  $scope.values = [
    1,2,3,4
    ];
  $scope.update=function(){
    console.log("the value is "+ $scope.selected)
  }
})
.directive('jgRadio', function() {
    return {
      restrict:"E",
      scope:{
        values:"=",
        selected:"=",
        update:"&"
      },
      template: '<input ng-repeat="item in values" type="radio" value="{{item}}" ng-model="$parent.selected" ng-change="update()"></input>'
    };
  });

但是控制台日志输出之前选择的(plunker

有人可以看到我缺少什么吗?

4

2 回答 2

3

我想是子范围继承问题的典型案例。将模型绑定更改为包含选定值的对象并将对象绑定为两种方式绑定:-

$scope.selected = {value: 1};

并从您的指令中删除丑陋的$parent@$parent.selectedselected.value

 <input ng-repeat="item in values" type="radio" ng-value="item" ng-model="selected.value" ng-change="update()"></input>

PLNKR

原因是,在运行 ng-change 之后,需要运行摘要循环来更新指令消费者上的 2 路绑定的值。ng-change并且只有在函数评估完成后才会运行摘要循环。console.log($scope.selected)因此,当您在父控制器内部执行操作时,在您的函数中,2 路绑定变量的值尚未在父范围内更新。因此,您会看到 console.log 显示范围的先前值,并且绑定在摘要周期后仍会更新。当您将对象而不是原始对象绑定到 2 路绑定时,2 路绑定范围变量和父控制器范围变量都指向同一个对象引用并且更改会立即反映,也更喜欢使用ng-value反对,value={{item}}尤其是在处理无线电时输入。

将给定的表达式绑定到 input[select] 或 input[radio] 的值,以便在选择元素时,将该元素的 ngModel 设置为绑定值。

于 2014-10-17T21:20:43.920 回答
0

我的解决方案:http: //plnkr.co/edit/FcivQTotZAyjh5EvFNRr

  $scope.update=function(){
    $timeout(function(){
      console.log("the value is "+ $scope.selected);
    })
  }
于 2014-10-17T21:07:12.507 回答