Angular指令演示:
<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> ' +
'</span>' +
'</div>'
};
});
现在:
点击A1 - &gt; B1选择了
点击A2 - &gt; B2选中
点击B1 - &gt; A1未改变
点击B2 - &gt; A2没有改变
我想:
点击A1 - &gt; B1选择了
点击A2 - &gt; B2选中
点击B1 - &gt; A1选择了
点击B2 - &gt;选择A2
如何?
答案 0 :(得分:5)
一种方法是使用 $ parent (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> ' +
'</span>' +
'</div>'
};
});
答案 1 :(得分: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> ' +
'</span>' +
'</div>'
};
});
</script>