计算angularjs指令中的表达式';s编译函数
我正在构建一个自定义指令,它将根据属性值显示不同的HTML元素 比如说计算angularjs指令中的表达式';s编译函数,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我正在构建一个自定义指令,它将根据属性值显示不同的HTML元素 比如说 <my-directive show="text" value="123" /> <!-- this displays a text box --> <my-directive show="boolean" value="true" /> <!-- this shows a checkbox --> <my-directive show="myObje
<my-directive show="text" value="123" /> <!-- this displays a text box -->
<my-directive show="boolean" value="true" /> <!-- this shows a checkbox -->
<my-directive show="myObject.type" value="myObject.value" />
如何使角度表达式的结果可用于编译函数
.directive('myDirective', function() {
return {
restrict: 'E',
compile: function(el, attrs) {
if (attrs.show == 'text')
el.replaceWith(textTemplate)
else if (attrs.show == 'number')
el.replaceWith(numTemplate)
else if (attrs.show == 'boolean')
el.replaceWith(boolTemplate)
else if (attrs.show == 'timezone')
el.replaceWith(tzTemplate)
else if (attrs.show == 'datetime')
el.replaceWith(dtTemplate)
else if (attrs.show == 'date')
el.replaceWith(dateTemplate)
else if (attrs.show == 'time')
el.replaceWith(timeTemplate)
else
console.log("no input type matched "+attrs.show); // this always fires, with value 'myObject.type'
},
link: function() { .... }
}
在点击链接函数之前,您无法访问元素属性和作用域,从而无法将表达式解析为作用域上的值。这是一个完美的示例,可以在其中使用。创建隔离作用域还有另一个主要特性,它将使指令更加可重用
directive('myDirective', function() {
return {
restrict: 'E',
scope: {
show: '=show',
value: '=value'
},
compile: function(el, attrs) {
if ($scope.show === 'text'
...
谢谢你的回答。但是在编译DOM时还没有注入作用域。我说得对吗?如果我这样写的话,它就行了。它将显示一个输入[文本]框。是的,因为您不需要范围来解析变量。在编译函数中,基本上不可能访问作用域来解析作用域上的变量。您是否尝试过将代码移动到Link函数而不是compile函数?