2013-11-28 57 views
6

角指令演示:角指令:绑定到变量在父范围

jsfiddle

<div ng-app="myApp"> 
<script> 
    function Contrl($scope){ 
     $scope.parval = 0; 
     $scope.items = [ 
      {id: 1, text: '1'}, 
      {id: 2, text: '2'}, 
      {id: 3, text: '3'} 
     ]; 
    } 
</script> 
<div ng-controller="Contrl"> 
    A: <input type="radio" value="1" ng-model="parval">1</input> 
    <input type="radio" value="2" ng-model="parval">2</input> 
    <input type="radio" value="3" ng-model="parval">3</input> 
    <item parval="parval" items="items"></item> 
</div> 

angular.module('myApp', []) 
.directive('item', function() { 
    return { 
     restrict: 'E', 
     replace: true, 
     scope: { 
      parval: '=', 
      items: '=' 
     }, 
     template: '<div>' + 
     'B: <span ng-repeat="i in items">' + 
       '<input value="{{i.id}}" type="radio" ng-model="parval">{{i.text}}</input>&nbsp;' + 
      '</span>' + 
     '</div>' 
    }; 
}); 

目前:
单击A1 - > B1选择
点击A2 - > B2选择

点击B1 - > A1没有改变
点击B2 - > A2没有改变

我想:
单击A1 - > B1选择
点击A2 - > B2选择

点击B1 - > A1选择
点击B2→A2选择

如何?

回答

4

你正在使用的原语,你应该避免使用文字符号,因为ng-repeat创建一个新的范围。下面的代码将解决你的问题

<div ng-controller="Contrl"> 
    A: <input type="radio" value="1" ng-model="parval.value">1</input> 
    <input type="radio" value="2" ng-model="parval.value">2</input> 
    <input type="radio" value="3" ng-model="parval.value">3</input> 
    <item parval="parval" items="items"></item> 
</div> 
    <script> 
     function Contrl($scope) { 
      $scope.parval = { value: 0 }; 
      $scope.items = [ 
       { id: 1, text: '1' }, 
       { id: 2, text: '2' }, 
       { id: 3, text: '3' } 
      ]; 
     } 
     angular.module('myApp', []) 
.directive('item', function() { 
    return { 
     restrict: 'E', 
     replace: true, 
     scope: { 
      parval: '=', 
      items: '=' 
     }, 
     template: '<div>' + 
     'B: <span ng-repeat="i in items">' + 
       '<input value="{{i.id}}" type="radio" ng-model="parval.value">{{i.text}}</input>&nbsp;' + 
      '</span>' + 
     '</div>' 
    }; 
}); 
    </script> 
+0

从父母传递价值的子组件我们可以使用绑定:{ text:'<' },但是对于孩子到父母需要做些什么? (tet将显示给父母的孩子) – cracker

5

一种方法是使用$父 (NG-模型= “$ parent.parval”)

angular.module('myApp', []) 
.directive('item', function() { 
    return { 
     restrict: 'E', 
     replace: true, 
     template: '<div>' + 
     'B: <span ng-repeat="i in items">' + 
       '<input value="{{i.id}}" type="radio" ng-model="$parent.parval">{{i.text}}</input>&nbsp;' + 
      '</span>' + 
     '</div>' 
    }; 
});