角度指令演示:
<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 – > B1选中
点击A2 – > B2选中
点击B1 – > A1没变
点击B2 – > A2没变
我想要:
点击A1 – > B1选中
点击A2 – > B2选中
点击B1 – > A1选中了
点击B2 – > A2选中
怎么样?
你正在使用原语,你应该避免使用文字表示法,因为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',function () { return { restrict: 'E',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>