Assuming I have a directive "mydirect" with a template that contains a lot of divs with a lot of nested classes. For example:
<div class="mydirect"> <div class="classA"> <div class="subclassA"> <div class="subclassB"> </div> <div class="classB"></div> </div>
I noticed that despite having the classnames in a css file ("mydirectstyle.css") and it being included in index.html, using my directive:
angular.module("MyApp", []). directive('mydirect', function() { return { restrict: 'E', replace: true, template: '-All that Html here-' }; });
None of the CSS properties are applied to it whatsoever. What is the best way to apply all my styles to those multiple classes? Can it be done such that I don't have to manually select each element and set individual CSS properties?
My index.html page contains a <mydirect> </mydirect>
that gets replaced by the directive template shown above.
AngularJS ng-style DirectiveThe ng-style directive specifies the style attribute for the HTML element. The value of the ng-style attribute must be an object, or an expression returning an object. The object consists of CSS properties and values, in key value pairs.
AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using "directive" function. A custom directive simply replaces the element for which it is activated.
NgStylelinkAn attribute directive that updates styles for the containing HTML element. Sets one or more style properties, specified as colon-separated key-value pairs. The key is a style name, with an optional .
Its much easier to use actual element names to create directives in your DOM rather than trying to use the class method. For two reasons: 1) its much more readable to have <mydirect>
vs <div class="mydirect">
and 2) you can get the same ease of styling by just using the proper css syntax.
Leave your directive just the way it is, except change it to restrict: 'EA'
(docs for that here) and replace: false
, as shown here:
.directive('mydirect', function() { return { restrict: 'EA', replace: false, template: '-All that Html here-' }; });
Here are the options you can now use and how to configure the corresponding CSS to get the styles you want, as shown in this jsbin:
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With