$parse

$parse将一个AngularJS表达式转换成一个函数

html

<div ng-app="MyApp">
    <div ng-controller="MyController">
        <input type="text" ng-model="expression" />
        <div>{{ParsedValue}}</div>
    </div>
</div>

js

angular.module("MyApp",[])
.controller("MyController", function($scope, $parse){
    $scope.$watch("expression", function(newValue, oldValue, context){
        if(newValue !== oldValue){
            var parseFunc = $parse(newValue);
            $scope.ParsedValue = parseFunc(context);
        }
    });
});

我们使用$watch监测input输入框的变化,每当输入框中的表达式的值发生变化时,我们都会解析它,我们可以尝试向输入框中输入"1+1",然后就会看到下面显示2。

原文地址:https://www.cnblogs.com/smallzhu/p/7119783.html