In an old side project, an application that suggests meals based on calorie input, with AngularJS for the frontend I had been using theng-style
directive to set the CSS styles in the template.
The controller looked like this:
(function(){angular.module('foodApp').controller('calorieCtrl',calorieCtrl);functioncalorieCtrl(){varvm=this;vm.styleCalorieInput={"background-color":"#3cb9c6","border-color":"transparent","border-radius":"10px"};vm.styleError={"color":"#f3c4a3"};...}();
Here I am using thecontrollerAs syntax to create a view model I can bind my data to so I can access it in the template like so:
...<divclass="well"ng-style="vm.styleCalorieInput"><spanng-style="vm.styleError">...</span></div>...
Even though this approach works I didn't like that I was setting the styles in the component, I wanted to define aseparate stylesheet for each component like I can with Angular and still define stylesheets for the entire application in a single file if I wanted to.
I foundangular-route-styles that allows me to declare route-specific styles using the$routeProvider
service and it solves my problem perfectly.
I used it by copyingroute-styles.js
into mylib
folder and included the file inindex.html
like so:
<!DOCTYPE html><html ng-app="foodApp">... <body ng-view> <script src="/lib/route-styles.js"></script> ... </body></html>
Now we need to addrouteStyles
as a module dependency toapp.js
and add thecss
property and value (where to find the css file(s)) to thewhen
route definition.
(function(){// Adds `routeStyles` along with `ngRoute` dependencyangular.module('foodApp',['ngRoute','routeStyles']);functionconfig($routeProvider){$routeProvider.when('',{templateUrl:'/calorie/calorie.view.html',controller:'calorieCtrl',controllerAs:'vm',css:'/calorie/calorie.css'}).otherwise({redirectTo:'/'});}angular.module('foodApp').config(['$routeProvider',config]);})();
Now I could delete all the style data bindings from the controller and theng-style
directives from the view. The controller now looks like this with the deleted part commented out:
// calorie/calorie.js(function(){angular.module('foodApp').controller('calorieCtrl',calorieCtrl);functioncalorieCtrl(){varvm=this;/** vm.styleCalorieInput = { "background-color": "#3cb9c6", "border-color": "transparent", "border-radius": "10px" }; vm.styleError = { "color": "#f3c4a3" }; */...}();
And in the view, I changed theng-style
directives to classes with similar names (there are better ways to do this):
...<divclass="well styleCalorieInput"><spanclass="styleError">...</span></div>...
And moved the CSS properties to a newly createdcalorie.css
file in the same folder:
.styleCalorieInput{background-color:#3cb9c6;border-color:transparent;border-radius:10px;}styleError{color:#f3c4a3;}
If you're curious, you can read more about howTennisgent implemented his solutionhere on StackOverflow.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse