【问题标题】:AngularJS two-way data binding not working properly in directiveAngularJS双向数据绑定在指令中无法正常工作
【发布时间】:2016-07-11 11:57:28
【问题描述】:

我正在尝试使用 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;

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

【问题讨论】:

  • 您能说明如何将指令添加到 html 代码中吗?
  • 当然,我更新了。
  • list 包含什么?
  • 我放了列表内容。

标签: angularjs data-binding scope ng-repeat directive


【解决方案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

希望对你有帮助。

【讨论】:

  • @Dago 我很高兴它有所帮助。 :)
【解决方案2】:

尝试将范围变量作为对象,例如

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    相关资源
    最近更新 更多