gpt4 book ai didi

angularjs - 指令不插值,在模板字符串中

转载 作者:行者123 更新时间:2023-12-04 23:56:37 25 4
gpt4 key购买 nike

我正在尝试有条件地构建模板。我得到了一个带有一些 div 和 span 的 k2plugin 指令。根据 pluginui 属性,我想在模板末尾插入另一个指令。接下来的我的代码插入了除 pluginui 之外的所有内容
例如,最后一个 div 结果为:

<div {{pluginui}} width='300' height='420'></div>

{{pluginui}} 是文字,而它应该插入以触发另一个指令。
有趣的是,如果我将 {{pluginui}} 放在同一行的其他位置(例如在标签之间,它会被插值。

我怎么了?
app.directive("k2plugin", function () {
return {
restrict: "A",
scope: true,
link: function (scope, elements, attrs) {
console.log ("creating plugin");

// this won't work immediatley. attribute pluginname will be undefined as soon as this is called.
scope.pluginname = "Loading...";
scope.pluginid = null;

// observe changes to interpolated attributes

// [...] observe name, id, width, height

attrs.$observe('pluginui', function(value) {
console.log('pluginui has changed value to ' + value);
scope.pluginui = attrs.pluginui + "viewport";
});

},
template: "<div>\
<div>\
<span>{{pluginname}}</span>\
<span ng-click=\"resize(pluginid)\">_</span> <span ng-click=\"remove(pluginid)\">X</span>\
</div>\
<div {{pluginui}} width='{{pluginwidth}}' height='{{pluginheight}}'></div>\
</div>",
replace: true,
};
});

app.directive("canvasviewport", function () {
return {
restrict: "A",
scope: true,
link: function (scope, elements, attrs) {
console.log ("creating canvas viewport");
},
template: "<canvas width='{{pluginwidth}}' height='{{pluginheight}}'></canvas>",
replace: true
};
});

app.directive("divviewport", function () {
return {
restrict: "A",
scope: true,
link: function (scope, elements, attrs) {
console.log ("creating div viewport");
},
template: "<div style=\"width='{{pluginwidth}}' height='{{pluginheight}}'\"></div>",
replace: true
};
});

app.directive("autoviewport", function () {
return {
restrict: "A",
scope: true,
link: function (scope, elements, attrs) {
console.log ("creating auto viewport");
},
template: "<canvas width='{{pluginwidth}}' height='{{pluginheight}}'></canvas>",
replace: true
};
});

最佳答案

我认为 Angular 不会将某些内容插入到指令名称中。 {{}}(自动)设置 $watch。当 $watch 注意到变化时,它会更新 View ,但它不会调用 $compile,这是我认为需要在这里发生的。

所以,我会尝试在指令的链接函数中生成 HTML/模板,然后 $compile 它。就像是:

scope.$watch('pluginui', function(newValue) {
var jqLiteWrappedElement = angular.element('<div ' + newValue + ' width=...');
element.replaceWith(jqLiteWrappedElement);
$compile(jqLiteWrappedElement)(scope);
})

记得注入(inject) $compile进入指令。

关于angularjs - 指令不插值,在模板字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15485288/

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