[英]how can i share attributes on a parent directive with a child directive
如果您看一下http://jsfiddle.net/Zuriel/fdrtpjgd/
我的问题是如何将属性从父指令传递给嵌套的子指令。
假设父母和孩子是<container><insides></insides></container>
如果您看我的小提琴,您会发现孩子需要一些示波器帮助。 如果我使用$ scope,那么我会获得通过,但每个指令的作用域都相同,这很糟糕。 但是,如果我使用作用域,则它在每个指令内部都起作用,但是parent属性没有通过。 我需要编译吗? 通过和编译? 或者我可以通过链接来执行此操作,而我只是缺少一些东西。
app.directive('container', function() {
return {
restrict: 'EA',
replace: true,
transclude: true,
$scope: {
passthrough: '@'
},
link: function($scope, element, attrs) {
$scope.passthrough = attrs.greeting;
console.log($scope.passthrough);
},
template: '<div class="container">{{passthrough}} <div ng-transclude></div></div>'
}
});
app.directive('insides', function() {
return {
restrict: 'EA',
replace: 'true',
require: '^container',
transclude:true,
//template: '<div class="insides">{{passthrough}} <span ng-transclude></span></div>'
template: function ($scope) {
console.log($scope.passthrough);
return '<div class="insides">{{ passthrough }} <span style="color:red" ng-transclude></span></div>';
},
}
});
请按照此处的回答,我认为它将为您提供帮助
http://jsfiddle.net/Wijmo/MTKp7/
这里有一些代码示例
angular.module("btst", []).
directive("btstAccordion", function () {
return {
restrict: "E",
transclude: true,
replace: true,
scope: {},
template:
"<div class='accordion' ng-transclude></div>",
link: function (scope, element, attrs) {
// give this element a unique id
var id = element.attr("id");
if (!id) {
id = "btst-acc" + scope.$id;
element.attr("id", id);
}
// set data-parent on accordion-toggle elements
var arr = element.find(".accordion-toggle");
for (var i = 0; i < arr.length; i++) {
$(arr[i]).attr("data-parent", "#" + id);
$(arr[i]).attr("href", "#" + id + "collapse" + i);
}
arr = element.find(".accordion-body");
$(arr[0]).addClass("in"); // expand first pane
for (var i = 0; i < arr.length; i++) {
$(arr[i]).attr("id", id + "collapse" + i);
}
},
controller: function () {}
};
}).
directive('btstPane', function () {
return {
require: "^btstAccordion",
restrict: "E",
transclude: true,
replace: true,
scope: {
title: "@",
category: "=",
order: "="
},
template:
"<div class='accordion-group' >" +
" <div class='accordion-heading'>" +
" <a class='accordion-toggle' data-toggle='collapse'> {{category.name}} - </a>" +
" </div>" +
"<div class='accordion-body collapse'>" +
" <div class='accordion-inner' ng-transclude></div>" +
" </div>" +
"</div>",
link: function (scope, element, attrs) {
scope.$watch("title", function () {
// NOTE: this requires jQuery (jQLite won't do html)
var hdr = element.find(".accordion-toggle");
hdr.html(scope.title);
});
}
};
})
错别字:
$scope: {
passthrough: '@'
},
link
删除“ $”符号; 而且您不需要从attrs.greeting进行分配。
...注释掉...
link: function($scope, element, attrs) {
//$scope.passthrough = attrs.greeting;
console.log($scope.passthrough);
},
应该管用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.