我想创建排序顶部,父级和 sub 的嵌套指令。
<div ng-app="app">
<top>
<parent>
<sub global-name="global"></sub>
</parent>
</top>
</div>
我的jsvascript是:
angular.module("app",[]);
angular.module("app").directive("top",function(){
return {
restrict: "E",
transclude: true,
template: "<div ng-transclude></div>"
}
});
angular.module("app").directive("parent", function(){
return {
restrict: "E",
controller: function($scope){
$scope.global = {
name: "parent directive"
};
},
link: function(scope){
},
transclude: true,
template: "<div ng-transclude></div>"
}
});
angular.module("app").directive("sub", function(){
return {
restrict: "E",
require:"^parent",
scope: {
global: "=globalName"
},
controller: function(){
},
link: function(scope){
scope.title = scope.global;
console.log(scope.global);
},
template: "{{global.name}}"
}
});
这是有效的。 JSfiddle code就在这里。但;
如果我隔离父指令范围,我无法从子指令访问父的global
对象。
angular.module("app").directive("parent", function(){
return {
restrict: "E",
controller: function($scope){
$scope.global = {
name: "parent directive"
};
},
link: function(scope){
},
transclude: true,
template: "<div ng-transclude></div>",
scope: {}
}
});
这不起作用。 Jsfiddle is here
答案 0 :(得分:0)
当然,你无法确定isolted范围的所有要点,因为你的父指令和子指令都有孤立的范围,但这并不起作用。
如果您希望2指令具有父/子关系,则使用父控制器API与子指令进行通信。
检查这个小提琴:https://jsfiddle.net/tp1pc31z/
angular.module("app").directive("parent", function(){
return {
restrict: "E",
controller: function($scope){
this.global = {name:"parent directive"};
},
link: function(scope){
},
transclude: true,
template: "<div ng-transclude></div>",
scope: {}
}
});
angular.module("app").directive("sub", function(){
return {
restrict: "E",
require:"^parent",
scope:{},
controller: function(){
},
link: function(scope, element, attr, parentCtrl){
console.log("parent : "+parentCtrl);
scope.title = parentCtrl.global;
console.log(scope.title.name);
},
template: "Global : {{title.name}}"
}
})
答案 1 :(得分:0)
以下是采用不同方法的解决方案 - Fiddle
JS
angular.module("app",[]);
angular.module("app").directive("top",function(){
return {
restrict: "E",
template: "<parent></parent>"
}
});
angular.module("app").directive("parent", function(){
return {
restrict: "E",
controller: function($scope){
$scope.global = {
name: "parent directive"
};
},
link: function(scope){
},
template: "<sub global='global'></sub>",
scope: {}
}
});
angular.module("app").directive("sub", function(){
return {
restrict: "E",
scope: {
global: "="
},
controller: function(){
},
link: function(scope){
scope.title = scope.global;
console.log(scope.global);
},
template: "{{global.name}}"
}
});
标记
<div ng-app="app">
<top>
</top>
</div>