Angular指令:绑定到父作用域中的变量

时间:2013-11-28 12:07:30

标签: angularjs angularjs-directive angularjs-scope

Angular指令演示:

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 - &gt; B1选择了
点击A2 - &gt; B2选中

点击B1 - &gt; A1未改变
点击B2 - &gt; A2没有改变

我想:
点击A1 - &gt; B1选择了
点击A2 - &gt; B2选中

点击B1 - &gt; A1选择了
点击B2 - &gt;选择A2

如何?

2 个答案:

答案 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>&nbsp;' +
            '</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>&nbsp;' +
            '</span>' +
        '</div>'
    };
});
    </script>
相关问题