Ng-style
<input type= "button" value= "Set Color" ng-click= "Mystyle={color: ' Red '}" ><input type= "button" value= "set Background "ng-click=" mystyle={' background-color ': ' Blue ', Color: ' Black '} ' ><span ng-style= ' MyStyle ' > Sample text</span>
PS:Ng-style The specified expression 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:
Scope. $watch (Attr.ngstyle, function ngstylewatchaction (Newstyles, oldstyles) { if (oldstyles && ( Newstyles!== oldstyles) { ForEach (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 <body ng-app= "" class= "Ng-scope" >2 <input type= "button" value= "Change font Color" ng-click= "Mystyle={color: ' Red ' } ">3 <input type=" button "value=" Change background color "ng-click=" mystyle={' background-color ': ' Blue '} ">4 < Input type= "button" value= "clear" ng-click= "mystyle={}" >5 <br>6 <span ng-style= "MyStyle" style= "Color:yellow;" >sample text</span>7 <pre class= "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.
Angular.js directives