我一直在尝试使用 angularjs 来创建我自己的应用程序,然后我想到了以下想法:
我想制定一个指令来制作可与 Bootstrap 网格系统一起使用的响应式方形 div。
在继续之前,我已经彻底搜索了过去 4 个小时,虽然我发现了一些有趣的方法,但没有一个能给我解决方案。
所以我想出了下面的代码:
var app = angular.module('ClientsApp', []);
app.directive('wh', function(){
return function(scope, element, attrs){
var x = element.css[width];
element.css({
'width': x,
'height': x,
'border-radius':'1rem',
});
};
});
但是,我无法让它工作(我已经使用 angular 两天了)。 Intead 如果我这样做:
var app = angular.module('ClientsApp', []);
app.directive('wh', function(){
return function(scope, element, attrs){
var x = element.css[width];
element.css({
'width': **x + 'em'**,
'height': **x + 'em'**,
'border-radius':'1rem',
});
};
});
当 x in 属性 wh='x' 设置时有效。
我想要的是使“x”(在 angularjs 脚本中)等于 col-vw-x Bootstrap 类给出的宽度值,所以当我写:
根据 Bootstrap 类,我自动得到一个方形 div。
đây là mộtworking plunker based on your code.
在我的 HTML 中我有:
我的指令是这样的:
app.directive('wh', function(){
return function(scope, element, attrs){
var width = attrs.class.substring(1+attrs.class.lastIndexOf('-'));
console.log('Directive width: '+width);
var x = element.css[width];
element.css({
'width': width + 'em',
'height': width + 'em',
'border-radius':'1rem',
});
};
});
在我的示例中,基本上我读取了类属性并获得了 col-sm-4。查找最后一个“-”并获取字符串的其余部分(即我的示例中的 4。)然后我使用了您的代码并且它有效。
你可能想在指令中添加一些错误检查,因为我正在使用 indexOf 和 substring,但总体思路就在那里。
如果有帮助,请告诉我。
Tôi là một lập trình viên xuất sắc, rất giỏi!