认识 AngularJS中的$parse和$eval

$parse和$eval都是用来将表达式转为一个函数

$eval是scope的一个方法,$parse是一种全局可以使用的服务。

从api可以看出来$eval是一种使用当前上下文的特殊$parse

// `$parse`

$parse(expr)(context, locals);

// `$eval`:
//      expr:要解析的表达式
//      locals:上下文 

function(expr, locals) {
        return $parse(expr)(this, locals);
      }

认识 AngularJS中的$parse和$eval

使用


我们用添加一个可以修改表达式的input,并且监听表达式当值发生变化重新解析

<!DOCTYPE html>
<html ng-app="App">

    <body ng-controller="Ctrl">
        <div>{{sayName}}</div>
        <input type="text" ng-model="expr" />
        <script>
            angular.module("App", []).controller("Ctrl", ["$scope", "$parse", function($scope, $parse) {

                $scope.con = {
                    "name": "tom",
                    "myname": "chenjy"
                };

                $scope.expr = "'my name is '+ con.name";
                $scope.sayName = $parse($scope.expr)($scope)

                $scope.$watch("expr", function(newValue, oldValue, context) {
                    if(newValue !== oldValue) {
                        $scope.sayName = $parse(newValue)(context)
                    }
                });

            }]);
        </script>
    </body>
</html>

other

监听enter按键事件

                $scope.enterEvent = function() {
                    console.log("Press Enter!");
                };
            }]).directive('ngEnter', ["$parse", function($parse) {
                return function(scope, element, attrs) {
                    element.bind("keydown keypress", function(event) {
                        console.log(event);
                        if(event.which === 13) {
                            scope.$apply(function() {
                                scope.$eval(attrs.ngEnter);
                                /*$parse(attrs.ngEnter)(scope);*/
                            });
                            event.preventDefault();
                        }
                    });
                };
            }]);
        </script>
    </body>
</html>

猜你喜欢

转载自www.linuxidc.com/Linux/2019-04/158202.htm