AngularJs,从嵌套的ng-repeat内的指令访问父范围

时间:2015-09-24 08:03:01

标签: javascript angularjs

这是一个菜鸟问题。我正在寻找在嵌套的ng-repeat中访问指令内的父作用域的正确方法。这正是我的意思:

<div ng-app="myApp" ng-controller="myCtrl">
    <div ng-repeat="section in sections">
        {{section.Name}}
        <div ng-repeat="item in section.Items" ng-init="parent = section">
            <span class="menuItem">{{item}}</span>
        </div>
    </div>
</div>

指令:

myApp.directive('menuItem', function () {
    return {
        restrict: 'C',
        link: function (scope, element, attrs) {
            console.log(scope.$parent.section.SectionId);
        }
    }
});

该指令附加到内部ng-repeat中的项目,我需要访问父对象的属性。问题是我无法直接访问父属性(使用范围。$ parent),因为ng-repeat创建了一个新的范围,我必须附加我在ng-repeat中设置的对象的名称(在这种情况下范围) 。$父部分):

<div ng-repeat="section in sections">

console.log(scope.$parent.section.SectionId);

JsFiddle:http://jsfiddle.net/7Lra7Loy/2/

因为我希望指令是通用的,所以它可以在其他ng-repeat块中使用,而不必强制在ng-repeat中使用相同的名称,我发现的唯一方法是使用ng-init ,在所有ng-repeat块中都是相同的(ng-init =&#34; parent = section&#34;):

<div ng-repeat="section in sections">
    {{section.Name}}
    <div ng-repeat="item in section.Items" ng-init="parent = section">
        <span class="menuItem">{{item}}</span>
    </div>
</div>

myApp.directive('menuItem', function () {
    return {
        restrict: 'C',
        link: function (scope, element, attrs) {
            console.log(scope.parent.SectionId);
        }
    }
});

JsFiddle:http://jsfiddle.net/7Lra7Loy/1/

有没有更好的方法来处理这种情况?还是我错过了什么?我搜索了一下,但我找不到任何真正有用的东西。

1 个答案:

答案 0 :(得分:1)

模板:

<div ng-app="myApp" ng-controller="myCtrl">
    <div ng-repeat="section in sections">
        {{section.Name}}
        <div ng-repeat="item in section.Items">
            <span class="menuItem" section="{{section}}">{{item}}</span>
        </div>
    </div>
</div>

指令:

myApp.directive('menuItem', function () {
    return {
        restrict: 'C',
        scope: {
            section: '@' // text-binding
            //section: '&' //one-way binding
            //section: '=' //two-way binding
        },
        link: function ($scope, element, attrs) {
            console.log($scope.section);
        }
    }
});

JsFiddle:https://jsfiddle.net/nrkmn/26zhqbjg/