Angular Js (4) -- Filter & $apply & $run

Keywords: angular Javascript JSON Attribute

$scope - Local scope

  • scope.watch - Monitor data changes (as mentioned earlier)
  • scope.apply
    As mentioned in the previous article, in order to achieve data changes, views can also automatically follow changing requirements. Modify scope.name directly in the setTimeout method of the native JS, and the property will not be changed after running until the specified time. There are two solutions: (1) directly using the timeout service provided by angular Js;
    (2) In setTimeout timer, the scope.apply() method can also be used.
    The code is as follows:

    <pre>
        <!DOCTYPE html>
        <html lang="en" ng-app="app">
        <head>
            <meta charset="UTF-8">
            <title>Title</title>
            <script src="js/angular.min.js"></script>
            <script type="text/javascript">
                var app=angular.module("app",[]);
                app.controller("Aaa",Aaa);
    
                function Aaa($scope){
                    $scope.name="hello";
    
                    //Method 1
                    /*$timeout(function(){
                        $scope.name="hi";
                    },2000);*/
    
                    setTimeout(function(){
                        //By modifying the setTimeout method of the native JS directly, the name value of the running result does not change to "hi"
                        //$scope.name="hi";
    
                        //Method two
                        $scope.$apply(function(){
                            $scope.name="hi";
                        })
                    },2000);
                }
    
            </script>
        </head>
        <body>
            <div ng-controller="Aaa">
                <p>{{name}}</p>
            </div>
    
        </body>
        </html>
    </pre>
    

The scope.apply(fn) method can monitor the change of attributes within the processing function. Once there is a change, it will affect the corresponding view.
In contrast, its advantages can be directly used in third-party libraries or native JS methods.
In fact, in the source code of Angular Js and events, it is also implemented by calling scope.apply(fn) method.

angular.module

Used to create a module and return a module object.
- Controller - Create a controller, as I mentioned earlier. (A module object can create multiple controllers)
- run

    <pre>
        <!DOCTYPE html>
        <html lang="en" ng-app="app">
        <head>
            <meta charset="UTF-8">
            <title>Title</title>
            <script src="js/angular.min.js"></script>
            <script type="text/javascript">
                var app=angular.module("app",[]);
                app.run(["$rootScope",function($rootScope){
                    $rootScope.name="hello";
                }])s
            </script>
        </head>
        <body>
            <!--&lt;!&ndash;div ng-controller="Aaa">&ndash;&gt;
                <p>{{name}}</p>
            </div>-->
            There is no need to write at this time. ng-controller Instructions can be parsed
            <p>{{name}}</p>
        </body>
        </html>
    </pre>

The function of run method is to initialize some global data, omit the operation of creating controller and introducing controller instructions on the page.

Note: The run method can only have rootScope global scope, not local scope.

Filter filter filter

  1. Writing style:
    In the expression, a pipe symbol "|" (vertical line) is added to the right of the variable, and then a filter is written. As follows:

    <pre>
        <div ng-controller="Aaa">
            <p>{{price | currency}}</p>//Running results: $22,122.00
            //Modification of currency symbols
            <p>{{price | currency:"Y"}}</p>
        </div>
    </pre>
    
  2. Transfer parameters
    The way the filter passes parameters: after the filter + ":" (colon) + parameters, as shown in the code above.
    If multiple parameters are to be passed, they are written as follows:
    <p>{{price | currency: "Y": two parameters: three parameters} </p>

  3. Built-in filters
    - currency - converting a series of numbers into currency
    - number - Converts a series of numbers into text format.
    <p>{{price | number}}</p><!--22,122-->
    When these numbers have decimal numbers, the number filter defaults to retain (intercept) three decimal places.
    If you want to set the number of decimal places reserved, you can pass a parameter, the code is as follows:
    <p>{{price | number:2}}</p><!--22,122.34-->
    - uppercase/lowercase - case-to-case conversion
    These two filters have no parameters to pass.
    - json - json strings can be formatted so that they can be displayed in line like objects. The code is as follows:
    <pre>{{{name | json}} </pre>, note that it is best written in the < pre> tag, because it can identify spaces and newline tags.
    - limitTo - Interception of arrays or strings
    <p> {{name | limitTo: 2} </p>// Print out "he"
    - date
    <p>{time | date} </p>/$scope.time= "34233332200"; milliseconds, output Feb 1, 1971
    To set a specific date format, you need to pass parameters to the date filter. angular provides us with many parameters for date filters, which can be viewed in official documents.
    <p>{{time | date: 'yyyy' }}</p>
    - orderBy - Sort arrays

            <pre>
                 app.controller("Aaa",function($scope){
                    $scope.arrName=[
                        {color:"red",age:"20"},
                        {color:"green",age:"25"},
                        {color:"yellow",age:"16"},
                        {color:"blue",age:"30"}
                    ];
                 }
    
                 <div ng-controller="Aaa">
                      // In this case, the alphabet of the corresponding value of "color" is sorted from small to large.
                     <p>{{arrName | orderBy: 'color'}}</p>
                      // In this case, the numbers corresponding to "age" are sorted from small to large.
                      <p>{{arrName | orderBy: 'age'}}</p>
                 </div>
            </pre>
    
        If you want to sort the "age" attribute in the "arrName" array from large to small, you need to add a second parameter to the orderBy filter, which is coded as follows: </br>.
        `<p>{{arrName | orderBy: 'age' : true }}</p>`
     - filter -- filter specified data </br>
     `p > {arrName | filter: `red'} </p >// run output [{color': `red', `age': `20'}] `</br >
     <font color="red">
        In the above code, the filter parameter can only be for the key value, which is useless for the key name. </br>
     </font>
     `p > {arrName | filter: `l'} </p >// run output [{color": `yellow', `age', `16', ``color', `blue', `age', `30'} ` </br >
    If you want to match the specified data exactly, you need to set the second parameter to true, the code is as follows: </br>
    `p > {arrName | filter: `l': true} </p > <! - run output [] - > `br >
    Since the key value in "arrName" is not "l", the filtered output is an empty array of "[]".
    
  4. Filter Extension
    - Combinable filters
    <p> {{name | limitTo: 2 | uppercase} </p> <! - Run output "HE" --> >
    - Use of filters in JS
    The filters used above are used after html expressions. The use of filters in JS is achieved through a service approach: $filter.
    Note: Services in angular need to be injected through dependency injection.

            <pre>
                <!DOCTYPE html>
                <html lang="en" ng-app="app">
                <head>
                    <meta charset="UTF-8">
                    <title>Title</title>
                    <script src="js/angular.min.js"></script>
                    <script type="text/javascript">
                        var app=angular.module("app",[]);
                        //Injection filter service
                        app.controller("Aaa",["$scope","$filter",function($scope,$filter){
                            $scope.name= $filter('uppercase')('hello');
                            //Parameters are added after they are separated by commas
                             $scope.price= $filter('number')('3423333.34988',2);
                        }])
    
                    </script>
                </head>
                <body>
                    <div ng-controller="Aaa">
                        <!-- Output capitalization HELLO"-->
                        <p>{{name}}</p>
    
                         <!--Output "3,423,333.35"-->
                         <p>{{price}}</p>
                    </div>
                </body>
                </html>
            </pre>
    
  5. Custom filter
    It is implemented by filter under angular.module method.

                <pre>
                    <!DOCTYPE html>
                    <html lang="en" ng-app="app">
                    <head>
                        <meta charset="UTF-8">
                        <title>Title</title>
                        <script src="js/angular.min.js"></script>
                        <script type="text/javascript">
                            var app=angular.module("app",[]);
                            //Injection filter service
                            app.controller("Aaa",["$scope","$filter",function($scope,$filter){
                               /*$scope.name="hello";*/
                               $scope.name=$filter("firstUpper")("great",2);
                            }])
    
                            //Custom filter
                            app.filter("firstUpper",function(){
                                //The "str" here is the attribute value that needs to be filtered
                                //The num here is the first parameter passed in to the filter.
                                return function(str,num){
                                    console.log(num);//Print out 2
                                    return str.charAt(0).toUpperCase()+str.substring(1);
                                }
                            });
                        </script>
                    </head>
                    <body>
                        <div ng-controller="Aaa">
                            <!-- Output " Hello"-->
                            <!--<p>{{name | firstUpper}}</p>
                            <p>{{name | firstUpper : 2 }}</p>-->
                            <!-- Output " Great"-->
                            <p>{{name}}</p>
                        </div>
                    </body>
                    </html>
                </pre>
    

Posted by Oubipaws on Wed, 12 Dec 2018 07:33:06 -0800