gpt4 book ai didi

angularjs - 另一个指令的 templateUrl 内的指令和传递属性

转载 作者:行者123 更新时间:2023-12-04 18:01:04 29 4
gpt4 key购买 nike

我有两个指令,我试图在另一个指令的 templateUrl 中使用某个属性调用一个指令,但我无法在第二个指令中获取已编译的属性值。代码是这样的:

第一个指令

app.directive('myDir', function() {
return {
link: function(scope, element, attrs, controller) {
scope.myVal='hello';
},
templateUrl: 'directive1.html',
scope: {}
}

directive.html

<div>
<child-dir attrval="{{myVal}}"></child-dir>
<div>

第二条指令

app.directive('childDir', function() {
return {
templateUrl: template(element,attrs) {
alert(attrs.attrval);
},
scope: {}
}

这里,attrs.attrval 是这样的 {{myVal}}。但我想要值 hello。谁能帮我?请注意两点:

1) 我正在使用 templateUrl。2) 我将作用域变量的值作为属性传递给子指令。

最佳答案

我遇到了同样的问题并最终找到了解决方案(可能不是最好的,但它对我有用)。你的例子和我的有点不同,但我想你的例子是:

父指令和 directive.html 相等,但子指令:

app.directive('childDir', function() {
return {
templateUrl: template(element,attrs) {
attrs.$observe("attrval", function(){
alert(attrs.attrval);
});
},
scope: {}
}

当在父指令中设置模板时,该值尚未设置,但子指令正在尝试使用它。使用“观察”,子指令可以在真正设置 attrval 时强制刷新。

如果不适合您,请告诉我,我会发布部分代码,以备不时之需。

关于angularjs - 另一个指令的 templateUrl 内的指令和传递属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35315078/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com