Mat*_*ood 5 javascript css angularjs gruntjs
我知道这听起来很傻但我正在编写一个让所有设计师创建风格指南的所见即所得编辑器.我已经非常着迷于角度的双向绑定,并且如果有可能在css表和ng-model输入字段之间进行双向绑定,那就很奇怪了.目前,我正在制作一个动态样式指南,允许设计师对页面的主要,次要颜色进行颜色选择.这些颜色将统一改变网站的整个主题,从样式表本身做这件事会很棒.
HTML
<input type="text" ng-model="color.primary" />
<button class="btn primary-color" />
Run Code Online (Sandbox Code Playgroud)
CSS
.primary-color {
background: {{color.primary}};
}
Run Code Online (Sandbox Code Playgroud)
js $ scope.color {primary:'00f',secondary:'#e58'}
我知道有很多指令喜欢ng-style和ng-class但我担心每个标签都必须是一个指令,因为一切都可以有一个ng-style/ng-class标签.因此,使我的代码不是很干,很难维护.
如果我想要一个动态的CSS风格指南怎么办?我可以将一个表格作为关键值对存储到像firebase一样的服务器,甚至可以实时绑定颜色的变化?我很确定这不可能只使用角度来实现...任何人都有预编译器或黑客的任何想法来完成这个任务,这样它会导致一个干净的风格的家伙吗?
这非常有趣.
您可以访问页面上的所有样式document.styleSheets,因此您只需要在样式上确定规则的范围.所以我要说我有这个课程:
.class {
font-size: 20px;
color: blue;
}
Run Code Online (Sandbox Code Playgroud)
jsfiddle如何实现工作表,这是添加到文档中的第三个样式表,所以我可以像这样分配到范围:
myApp.controller('TestController', ['$scope', function ($scope) {
$scope.styles = document.styleSheets[3].rules;
}]);
Run Code Online (Sandbox Code Playgroud)
这可以让你做一些事情,比如$scope.styles[0].style['color'] = 'red'将类改为颜色为红色.因为它是样式数组中的第一件事.
但这还不够酷,所以我们想创建一个指令,我们可以从ui更改这些指令.所以我们想知道类控制的所有东西,为它们创建控件,所以我们可以操作css字符串来获取所有这些.
接下来,我们必须在指令上创建一个临时范围内的对象,该对象以所有样式开始.原因是样式表有检查,所以当你输入类似的东西$scope.styles[0].style['color'] = 'g'并且它是红色时,它会输入一个输入,它只会重置为红色.
因此,我们为每个样式类型创建一个输入,使用我们的temp的ng-model,然后只是监听更改并尝试分配给样式表.
我创建了一个小提琴,我实现它,但指令看起来像这样.
myApp.directive('styler', function() {
return {
scope: {
styles: '='
},
restrict: 'EA',
template: '<div ng-repeat="type in types">{{type}} <input ng-change="Change(type)" ng-model="temp_styles[type]"/></div>',
link: function(scope, elt, attrs) {
// get the actual styles
var types = scope.styles.cssText.replace(/ /g, '').split('{')[1].split('}')[0].split(';');
scope.types = [];
scope.temp_styles = {};
// get rid of "" element at the end
types.pop();
for (var i in types) {
var split = types[i].split(':');
scope.types.push(split[0]);
scope.temp_styles[split[0]] = split[1];
}
scope.Change = function(type) {
scope.styles.style[type] = scope.temp_styles[type];
};
}
};
});
Run Code Online (Sandbox Code Playgroud)
酷炫,动态的双向绑定风格!
希望这有帮助!