使用AngularJS,如果元素是transcluded指令的克隆,你如何为元素赋予自己的范围?
例如,说我有以下HTML:
<body>
<chicken></chicken>
</body>
以及以下指令:
app.directive('chicken', [
'$rootElement',
function($rootElement) {
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<div class="chicken" ng-transclude></div>',
scope: {},
link: function(scope, element, attrs) {
scope.nature = 'timid';
var egg = element.clone();
$rootElement.append(egg);
}
};
}
]);
如何确保egg
有自己的范围?
答案 0 :(得分:1)
您创建一个新范围并将其链接:
link: function(scope, element, attrs) {
scope.nature = 'timid';
var egg = element.clone();
var childScope = $rootElement.scope().new();
$compile(egg)(childScope);
$rootElement.append(egg);
}