请参考下面的代码。
我想避免使用 ng-trasclude,因为它是额外的包装元素,+ ng-transclude 制作自己的范围。所以我的目标是最终渲染<div foo title="FOO!">FOO!</div>
。
$compile(el.html())(scope)
中断,因为它再次需要一个包装元素。
template: "<div ng-transclude></div>"
将无法访问scope.title
。
谢谢
编辑 新增链接:https://plnkr.co/edit/R1CAc5pksOVMJoFLhsTu?p=preview 和片段
angular.module('app', []).directive('foo', function() {
return {
restrict: 'A',
scope: {
title: '@'
}
}
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
</head>
<body>
<div foo title="FOO">{{title}}</div>
<span>expecting "FOO!" above this line, but, sigh...</span>
</body>
</html>
编辑 2
我想保留隔离范围,以便通过scope: {title:'@'}
应用属性(<div foo title="FOO!">{{title}}</div>
。
编辑 3
更新了代码段。
您为指令分配了隔离范围。 如果要访问,请按给定scope : true
将其设置为本地。
angular.module('app', []).directive('foo', function() {
return {
restrict: 'A',
scope: {
title : '='
},
template : '{{title}}'
}
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
</head>
<body>
<div foo title="'Foo!'"></div>
<span>expecting "FOO!" above this line, but, sigh...</span>
</body>
</html>
你需要有一个模板来呈现scope.foo
所以在你的指令中你需要指定一个模板。 此外,如果您不会有任何来自父级的值,则不必scope: {}
因为已经为您创建范围
angular.module('app', []).directive('foo', function() {
return {
restrict: 'A',
template: '<span ng-bind="foo"></span>', // <-- add this line
link: function(scope, el) {
scope.foo = 'FOO!';
}
}
});
试试看
link: function(scope, el,attr) {
scope.$parent.foo = "foo"
scope.foo = 'FOO!';
}