AngularJS 指令中的双向数据绑定无法正常工作

AngularJS two-way data binding not working properly in directive

我正在尝试使用 ng-repeat 实现单选按钮列表。 typeList.html

<div ng-repeat="type in types" >
    <input type="radio" id={{type.id}} name="{{type.name}}"  ng-model="result" ng-value="type.id" >
    {{type.name}}
    <div> Result {{result}} </div> //result is changing only in the row of clicked radio-button. It should change in every row.(two way data-binding).
</div>

指令:

angular.module('app').directive('myList',function(){
        return{
            restrict: 'A',
            scope: {
                types: '=',   //here list is passed to be printed with ng-repeat
                result: '='   //here I want to store which radio-button was selected last time by id
            },
            templateUrl: 'html/typeList.html'
        };


    });

指令具有隔离作用域。我正在传递两个参数。要使用单选按钮和结果对象打印的列表,该对象在父范围中存储答案(id-上次单击的单选按钮)。不幸的是,每当我点击单选按钮时,我的结果只会在本地发生变化。

 Passing parameters to my directive.
 <div my-list types="list" result="selected"></div>



  Passed list and result paramater from controller to myList directive.

 $scope.list   = [
        { id: 1, name:'Name 1' },
        { id: 2, name:'Name 2' },
        { id: 3, name:'Name 3' }
    ];

$scope.selected = -1;

如有任何帮助,我将不胜感激。

尝试像

一样将作用域变量作为对象

$scope.types = { list: {}, selected: 'radioValueThatNeedsToBeSelected' }

您必须将非原始对象传递给模型以获取其对两个 war 绑定的引用。只需将 selected 包装到一个对象中以供参考。

在你的控制器中使用。

$scope.list = [{
    id: 1,
    name: 'Name 1'
  }, {
    id: 2,
    name: 'Name 2'
  }, {
    id: 3,
    name: 'Name 3'
  }];
  $scope.ctrlModel = {
    selected: -1
  }

在标记中 'html/typeList.html'

<div ng-repeat="type in types" >
  <input type="radio" id={{type.id}} ng-model="result.selected" ng-value="type.id" >
     {{type.name}}
</div>
Result {{result.selected}}

工作Fiddle Demo

希望对您有所帮助。