假设我已经指示'测试'其独立范围为scope:{data:=}
并且我的另一个指令具有链接功能,如下所示
link : function (scope,ele,att){
var testData = {bla:123};
var a = $compile(<test data = testData></test>)(scope)
}
所以问题是如何将testData Object传递给测试指令
答案 0 :(得分:1)
Compiled元素获取您传入的作用域,因此将子作用域中所需的数据添加到父作用域中:
scope.data = toFoo
element.append($compile("<foo data='data' />")(scope))
看看示例
angular.module('myApp', [])
.directive('bar',
function($compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var toFoo = {
s: 'ome',
d: 'ata'
}
scope.data = toFoo
element.append($compile("<foo data='data' />")(scope));
}
};
}
)
.directive('foo',
function() {
return {
restrict: 'E',
scope: {
data: '='
},
replace: true,
template: "<div class='in'></div>",
link: function(scope, element, attrs) {
element.append(JSON.stringify(scope.data))
}
};
}
);
.out {
height: 100px;
width: 200px;
z-index: 1;
background-color: #ddd;
position: relative;
}
.in {
height: 50px;
width: 150px;
z-index: 2;
background-color: #333;
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div class="out" bar></div>
</div>