How to keep CSS classes unaffected by Angular controllers

不言
Release: 2018-11-06 15:26:52
Original
2654 people have browsed it

In Angular (and in general) I'm a big fan of keeping view logic outside of my controllers, and where I think this doesn't happen is with the use of CSS classes and ng-class.

You may not be familiar with ng-class, it is a special directive that allows binding expressions and placing them as the class of the element. A very common use of ng-class is like this:

<p ng-class="{{active}}">Class applied!</p><script>
    function MySimpleCtrl() {
        $scope.active = &#39;active&#39;;
        ...
Copy after login

So in the controller we set the specific class that should be displayed; So let's say we have a class "inactive." - we simply put $ The scope.active variable is set to "inactive" and we finally set the class in the view.

But ng-class is even better than that:

ng-class accepts three different types of values:

1. String value (name of class)

2. String array (class to be applied)

3. Object expression to be evaluated

The syntax of option 3 looks like this

ng-class="{object of key/value pairs}[expression to evaluate]"
Copy after login

Basically, ng-class evaluates the expression (in square brackets) and then uses it as the key of the object; the value associated with the key is the applied class.

This allows us to convert the $scope.active value to a true boolean (which is exactly how we use it) - with no view logic in the controller, the controller is easier to test and can be reused.

Here is a simple example:

<p ng-class="{true: &#39;active&#39;, false: &#39;inactive&#39;}[isActive]">
    Class applied
!</p><script>
    function MySimpleCtrl() {
        $scope.isActive = true;
Copy after login

If you are using some kind of conditional expression (i.e. toggle), then you can use another very similar syntax:

ng-class="{&#39;selected&#39;: isSelected, &#39;blue&#39;: isBlue}"
Copy after login

Here, if selected is true, the selected class will be applied, as will the blue class. Angular will apply as much realism as possible, so you can set classes to selected and blue.

The above is the detailed content of How to keep CSS classes unaffected by Angular controllers. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template