[英]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.