这是一个菜鸟问题。我正在寻找访问嵌套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中的项目,我需要访问父对象的属性。问题是我无法直接访问父属性(具有scope。$ parent),因为ng-repeat创建了一个新的范围,并且我必须附加在ng-repeat中设置的对象的名称(在这种情况下为scope 。$母公司部分):
<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 =“ parent = section”):
<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/
有没有更好的方法来处理这种情况?还是我只是想念一些东西?我搜索了一下,但是找不到任何真正有用的东西。
模板:
<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/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句