我正在AngularJS中为<mytextarea class="custom_mta default_mtastyle" width="30" height="40" x="150" y="50">text here</mytextarea>
通常我会拥有该示例的属性,但它不是一个全面的列表,我可能没有其中的一些。我必须将它们转换为CSS。 下面的代码不能很好地工作。例如,如果未定义宽度,则应为“auto”,而不是零,或者仅包含在css部分中。
.directive('mytextarea', function() {
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<div ng-transclude></div>',
link: function (scope, element, attrs) {
/* add unique properties for this directive */
var newcss = 'width:' + (attrs.width | 0) + 'px; height:' + attrs.height + 'px;';
attrs.$set('style', 'color:red;' + newcss);
/* remove attributes that are no longer needed */
element
.removeAttr('width')
.removeAttr('height');
/* and set a default class */
attrs.$set('class', 'default_subscreen ' + attrs.class );
}
}
有更好的方法来写这个吗?我尝试使用JSON语法:
var mystyle = {
position: 'absolute',
left: attrs.x,
width: attrs.width
}
attrs.$set('style', mystyle); // but mystyle is an object! should I use a filter?
也许我可以在值上运行函数?像(attrs.width)?attrs.width:0;
我还记得JS中的一些东西可以写成var s = "my string" + (attrs.width | 0)
。我在哪里可以获得有关它的扩展说明?
我还有一些组件在他们的指令中需要类似的逻辑,我正在寻找一个优雅的解决方案。