How to update variables in .less file dynamically

2019-01-27 04:06发布

问题:

I am very much new to AngularJS. I want to update the .less files variable dynamically. But didn't get how to access this .less file using AngularJS.

My code:

style.less

@bg-color: #484848;    
.header{ 
     background: @bg-color;
 }

I want to update @bg-color: #484848; present in the style.less file to some value input by user. How can I get this using AngularJS.

回答1:

You should run Less in browser to do this. If you load less.js in your HTML, the global less object come available, so you can use less.modifyVars() and less.refreshStyles() inside your angularJS code:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example78-production</title>

<link rel="stylesheet/less" type="text/css" href="color.less" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.1/angular.min.js"></script>

<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.3.1/less.min.js"></script>

</head>
<body ng-app="submitExample">
  <script>
  angular.module('submitExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.list = [];
      $scope.text = 'orange';
      $scope.submit = function() {
        if ($scope.text) {
        less.modifyVars({ color : $scope.text });
        }
      };
    }]);
</script>
<h1>Colored text</h1>
<form ng-submit="submit()" ng-controller="ExampleController">
  Enter text and hit enter:
  <input type="text" ng-model="text" name="text" />
  <input type="submit" id="submit" value="Submit" />
</form>
</body>
</html>

See: http://plnkr.co/5b1HTkneFXLMGVvXEG8j http://plnkr.co/edit/Z9tRY3Lol31PMnPUfxQi



标签: less