Use
The Ng-style property is used to set the CSS value of the element's Style property .
usage
<inputtype= "button"value= "Set Color"Ng-click= "Mystyle={color: ' Red '}"><inputtype= "button"value= "Set Background"Ng-click= "mystyle={' background-color ': ' Blue ', Color: ' Black '}"><spanNg-style= "MyStyle">Sample Text</span>
The expression specified by Ng-style must be a single-layered JSON object, with key and value corresponding to the name and value of the CSS property. Note If there are "-" connectors in the CSS property name, you need to enclose them in quotation marks.
Working principle
Ng-style code is simple, call the Jquery.css method, remove the last set CSS property (why?). ), add a new CSS property.
Ngstyle 's core code:
function ngstylewatchaction (Newstyles, oldstyles) { if (oldstyles && (newstyles!== Oldstyles) {function(val, style) {element.css (style, ');}); } if (newstyles) element.css (newstyles); true);
Legacy Issues
The Ng-style code is relatively simple, so it brings up some problems. Ng-style listen to the expression changes, the last set of the style to clear, but did not restore the value before the last set, it is possible to remove the previous style value.
1 <BodyNg-app=""class= "Ng-scope">2 <inputtype= "button"value= "Change font color"Ng-click= "Mystyle={color: ' Red '}">3 <inputtype= "button"value= "Change background color"Ng-click= "mystyle={' background-color ': ' Blue '}">4 <inputtype= "button"value= "Clear"Ng-click= "mystyle={}">5 <BR>6 <spanNg-style= "MyStyle"style= "Color:yellow;">Sample Text</span>7 <Preclass= "Ng-binding">mystyle={}</Pre>8 9 </Body>
The above code, "sample text" is displayed in yellow, click "Change Font Color" and "Change background color", guess "sample text" font is what color?
Yellow should be a more reasonable color, right? Red also makes sense, after all the last time did not change it! However, the system is actually the default color (black) because it was erased:(
Do not understand the source code for any consideration, as I understand, should be implemented according to one of the following two scenarios:
- When initializing, the backup user customizes the style. Monitor expressions, change, restore user-defined style, and then overwrite with the newly defined style. In the example above, the font color should be yellow.
- Do not do the erasure treatment, directly to the style cover.
Avoidance scenario, the CSS property manifest in an expression is always consistent.
One might ask why the use of Ng-style also uses the style attribute?
A: The Ng-style setting is intended to reduce the flickering of pages to the ANGULARJS processing stage after page initialization.
The Ng-style of AngularJS directive