2015-11-29 67 views
0

我想知道是否有可能将参数从html传递给css文件。是这样的:将绑定参数传递给CSS

//css 
.some-class [args]{ 
    color: $(args.color|default:'#fff') 
    height: $(args.height|default:'50px') 
} 
//html 
<body ng-app='App'> 
    <div ng-controlle="Ctrl"> 
     <div ng-class='some-class${{element}}'></div> 
    </div> 
</body> 
//js 
angular.module('App',[]) 
.controller('Ctrl',["$scope",function(){ 
    $scope.$on('EchangeColor',function(newColor){ 
     $scope.element.color = newColor 
    }) 
    $scope.$on('EchangeHeight',function(newHeight){ 
     $scope.element.height = newHeight 
    }) 
}]) 

回答

1

总之,因为style元素不是HTML DOM的一部分,你想做什么是不可能的。

然而,您可以创建一个自定义指令并添加一个CSS样式元素。

HTML:

<div ng-app="myApp" ng-controller="MyCtrl"> 
    <style angular-style>.css_class {color: {{angularStyle}};}</style> 
    <span class="css_class">{{angularStyle}} text with AngularJS</span><br> 
    <input type="text" ng-model="angularStyle"> 
</div> 

JS:

var app = angular.module('myApp', []); 

app.directive('angularStyle', function($interpolate) { 
    return function(scope, elem) { 
     var exp = $interpolate(elem.html()), 
      watchFunc = function() { return exp(scope); }; 

     scope.$watch(watchFunc, function (html) { 
      elem.html(html); 
     }); 
    }; 
}); 

app.controller('MyCtrl', function($scope) { 
    $scope.angularStyle = 'blue'; 
}); 

CODEPEN DEMO