修改指令中的模板(动态添加另一个指令)
Modify template in directive (dynamically adding another directive)
问题
通过自定义指令动态添加ng-bind属性,以便能够在自定义指令中使用ng-bind、ng-bind-html或ing-bind-html unsafe,而无需在任何位置手动添加到模板定义中。
示例
http://jsfiddle.net/nstuart/hUxp7/2/
断开的指令
angular.module('app').directive('bindTest', [
'$compile',
function ($compile) {
return {
restrict: 'A',
scope: true,
compile: function (tElem, tAttrs) {
if (!tElem.attr('ng-bind')) {
tElem.attr('ng-bind', 'content');
$compile(tElem)
}
return function (scope, elem, attrs) {
console.log('Linking...');
scope.content = "Content!";
};
}
};
}]);
解决方案
不知道。真的,我不明白为什么上面的小提琴不起作用。尝试了一下,去掉了额外的$compile。
变通办法
我可以通过在指令中添加模板值来解决这个问题,但这会将内容封装在一个额外的div中,如果可能的话,我希望能够做到这一点。(见小提琴(
第二个变通办法
请在此处查看小提琴:http://jsfiddle.net/nstuart/hUxp7/4/(正如Ikarus博士在下文中所建议的(。我现在认为这是一种变通方法,因为在进入链接功能之前,你仍然可以修改模板,并且应该找到/应用更改。
您可以在链接函数内部进行编译,如下所示:
angular.module('app').directive('bindTest', ['$compile', function ($compile) {
return {
restrict: 'A',
scope: true,
link: {
post: function(scope, element, attrs){
if (!element.attr('ng-bind')) {
element.attr('ng-bind', 'content');
var compiledElement = $compile(element)(scope);
}
console.log('Linking...');
scope.content = "Content!";
}
}
};
}]);
让我知道这对你有多好http://jsfiddle.net/bPCFj/
这种方式看起来更优雅(不依赖$compile(,适合您的情况:
angular.module('app').directive('myCustomDirective', function () {
return {
restrict: 'A',
scope: {},
template: function(tElem, tAttrs) {
return tAttrs['ng-bind'];
},
link: function (scope, elem) {
scope.content = "Happy!";
}
};
});
jsFiddle:http://jsfiddle.net/hUxp7/8/
根据Angular指令文档:您可以将template指定为表示模板的字符串,也可以指定为接受两个参数tElement和tAttrs(在下面的编译函数api中描述(并返回表示模板的串值的函数
源代码告诉一切!检查compileNodes()
函数及其对collectDirectives()
的使用。
首先,collectDirectives
查找单个节点上的所有指令。在我们收集了该节点上的所有指令后,然后将指令应用于该节点。
因此,当bindTest
指令上的compile
函数执行时,正在运行的$compile()
已经过了收集要编译的指令的时间点。
bindTest
指令中对$compile
的额外调用将不起作用,因为您没有将该指令链接到$scope
。您没有访问compile
函数中的$scope
的权限,但您可以在link
函数中使用相同的策略,在该函数中您可以访问$scope
你们太亲密了。
function MyDirective($compile) {
function compileMyDirective(tElement) {
tElement.attr('ng-bind', 'someScopeProp');
return postLinkMyDirective;
}
function postLinkMyDirective(iScope, iElement, iAttrs) {
if (!('ngBind' in iAttrs)) {
// Before $compile is run below, `ng-bind` is just a DOM attribute
// and thus is not in iAttrs yet.
$compile(iElement)(iScope);
}
}
var defObj = {
compile: compileMyDirective,
scope: {
someScopeProp: '=myDirective'
}
};
return defObj;
}
结果将是:
<ANY my-directive="'hello'" ng-bind="someScopeProp">hello</ANY>
- 向动态生成的DOM添加Angular自定义指令
- AngularJs从列表中动态创建指令
- AngularJS 指令的动态选项
- 如何动态禁用Angular指令
- 不适用于动态数据的Angular指令来自$http
- 动态更新Angular2指令中自定义属性的值
- 动态网格作为自定义指令
- 如何使用指令属性值创建动态模板
- AngularJS观察指令属性表达式,动态继承作用域
- AngularJS ng repeat指令,具有复杂的嵌套数据结构和动态键
- AngularJS没有't解析指令中动态加载的数据
- 如何将动态html与注入角度引导popover的指令一起使用
- 如果在transclusion之后添加,为什么指令下的动态元素具有错误的作用域
- Angularjs 使用指令动态添加和删除元素
- ng-repeat中的加载指令(动态模板URL)
- Angular JS:将一个指令动态插入另一个指令
- 从另一个指令动态添加、编译和链接ng类属性
- Angularjs使用指令动态添加引导程序类
- AngularJS -指令动态模板.变量被视为文本
- Angular指令动态模板不支持绑定