angular.js 中的嵌套和动态创建的指令
Nested and dynamically created directives in angular.js
我坚持了很长时间。
在一个指令中,我想基于一个函数动态创建另一个指令。我宁愿在每个 'tab' 指令中创建一个新指令,而不是有 4 个指令声明,也就是说每次在 DOM 元素中设置 tab 属性时。
这是代码的一部分(配置是一个工厂,用于配置一些东西):
.directive('tab', function(config) {
return {
require: '^panelHandler',
restrict: 'A',
scope: true,
link: function(scope, elem, attrs, ctrl) {
ctrl.addPane(scope);
scope.select = function() {
ctrl.select(scope);
};
},
};
})
.directive('page1', directiveConfigurer('page1.html'))
.directive('page2', directiveConfigurer('page2.html'))
.directive('page3', directiveConfigurer('page3.html'))
.directive('page4', directiveConfigurer('page4.html'));
function directiveConfigurer(fileName) {
newDirective.$inject = ['config'];
return newDirective;
function newDirective(config) {
var directive = {
restrict: 'E',
scope: true,
templateUrl: config.filesDirectory + fileName,
};
return directive;
}
}
感谢您的帮助。
编辑:
配置...
angular.module('appLogic', ['socket-factory', 'data-factory', 'panelHandler-module'])
.factory('config', function() {
return {
filesDirectory : '../../templates/pages/',
fieldsNumber : 5,
};
});
以及我需要的...
link: function(scope, elem, attrs, ctrl) {
ctrl.addPane(scope);
//.directive('page' + number, directiveConfigurer(name))
scope.select = function() {
ctrl.select(scope);
};
},
如果指令基本相同,除了模板 url,那么您可以只创建一个指令并提供具体的 url 路径作为属性:
<page src="page1.html">
为此,使用指令定义对象的 templateUrl
属性 函数:
.directive("page", function(){
return {
templateUrl: function(tElem, tAttr){
return "/base/path/" + tAttr.src;
},
//...
};
});
我坚持了很长时间。
在一个指令中,我想基于一个函数动态创建另一个指令。我宁愿在每个 'tab' 指令中创建一个新指令,而不是有 4 个指令声明,也就是说每次在 DOM 元素中设置 tab 属性时。
这是代码的一部分(配置是一个工厂,用于配置一些东西):
.directive('tab', function(config) {
return {
require: '^panelHandler',
restrict: 'A',
scope: true,
link: function(scope, elem, attrs, ctrl) {
ctrl.addPane(scope);
scope.select = function() {
ctrl.select(scope);
};
},
};
})
.directive('page1', directiveConfigurer('page1.html'))
.directive('page2', directiveConfigurer('page2.html'))
.directive('page3', directiveConfigurer('page3.html'))
.directive('page4', directiveConfigurer('page4.html'));
function directiveConfigurer(fileName) {
newDirective.$inject = ['config'];
return newDirective;
function newDirective(config) {
var directive = {
restrict: 'E',
scope: true,
templateUrl: config.filesDirectory + fileName,
};
return directive;
}
}
感谢您的帮助。
编辑:
配置...
angular.module('appLogic', ['socket-factory', 'data-factory', 'panelHandler-module'])
.factory('config', function() {
return {
filesDirectory : '../../templates/pages/',
fieldsNumber : 5,
};
});
以及我需要的...
link: function(scope, elem, attrs, ctrl) {
ctrl.addPane(scope);
//.directive('page' + number, directiveConfigurer(name))
scope.select = function() {
ctrl.select(scope);
};
},
如果指令基本相同,除了模板 url,那么您可以只创建一个指令并提供具体的 url 路径作为属性:
<page src="page1.html">
为此,使用指令定义对象的 templateUrl
属性 函数:
.directive("page", function(){
return {
templateUrl: function(tElem, tAttr){
return "/base/path/" + tAttr.src;
},
//...
};
});