gpt4 book ai didi

javascript - Angularjs - 使用指令来实例化其他指令?

转载 作者:可可西里 更新时间:2023-11-01 02:18:59 26 4
gpt4 key购买 nike

所以让我们在我的 HTML 中说我有这样的东西:

<tabcontent></tabcontent>

那么这个指令的 javascript 是这样的:

tabsApp.directive('tabcontent', function(){

var myObj = {
priority:0,
template:'<div></div>',
replace: true,
controller: 'TabCtrl',
transclude: false,
restrict: 'E',
scope: false,
compile: function (element, attrs){
return function (parentScope, instanceEle){
parentScope.$watch('type', function(val) {
element.html('<div '+val+'></div>');
});
}
$compile(parentScope);
},
link: function postLink(scope, iElement, iAttrs){}
};
return myObj;

});

正确解析 HTML,并在 Controller JS 中找到 type 的值。

so <tabcontent></tabcontent> is replaced with <div recipe></div> for example..

(那部分确实发生了)

所以我还有一个食谱指令:

tabsApp.directive('recipe', function(){

var myObj = {
priority:0,
template:'<div>TESTING</div>',
replace: true,
controller: 'TabCtrl',
transclude: false,
restrict: 'E',
scope: false,
compile: function (element, attrs){
return {
pre: function preLink(scope, iElement, iAttrs, controller){},
post: function postLink(scope, iElement, iAttrs, controller){}
}
},
link: function postLink(scope, iElement, iAttrs){}
};
return myObj;

});

这显然非常简单,仅用于测试。但是配方指令没有被处理...

这是怎么回事?

最佳答案

你需要改变两件事:

  1. recipe指令不得限于 E(元素)。如果您正在生成类似 <div recipe></div> 的指令,您必须至少将 A(属性)添加到 restrict指令配置的属性:

    app.directive('recipe', function() {
    return {
    restrict: 'E',
    ...
  2. 您需要编译tabcontent的HTML内容'watch' 之后的指令:

    app.directive('tabcontent', function($compile){
    return {
    ...
    link: function (scope, iElement, iAttrs) {
    scope.$watch('type', function(val) {
    iElement.html('<div '+val+'></div>');
    $compile(iElement.contents())(scope);
    });
    }
    ...

jsFiddle:http://jsfiddle.net/bmleite/n2BXp/

关于javascript - Angularjs - 使用指令来实例化其他指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14562679/

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