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

时间:2016-07-11 11:57:28

标签: angularjs data-binding scope ng-repeat 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'
        };


    });

指令具有孤立的范围。我传递了两个参数。用单选按钮打印的列表和在父范围内存储答案(上次点击了什么单选按钮)的结果对象。不幸的是,每当我点击单选按钮时,我的结果只会在本地更改。

 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;

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

2 个答案:

答案 0 :(得分:1)

您必须将非基本对象传递给模型以获取其对双战绑定的引用。只需将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

希望它有所帮助。

答案 1 :(得分:0)

尝试将范围变量作为对象

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