html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/angular.min.js"></script>
</head>
<body>
<div ng-app="MyApp">
<div ng-controller="MyController">
<h1>{{ParsedValue}}</h1>
//<input type="text" ng-model="expression"/>
</div>
</div>
</body>
js
1:
angular.module("MyApp", [])
.controller("MyController", function ($scope, $parse) {
var context = {
name: "王尼玛"
};
var expression = "'暴走 ' + name";
var parseFunc = $parse(expression);
$scope.ParsedValue = parseFunc(context);
});
2:
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);
}
});
});
3:
angular.module("MyApp", [])
.controller("MyController", function ($scope, $parse) {
$scope.context = {
add: function (a, b) {
return a + b;
},
mul: function (a, b) {
return a * b;
}
};
$scope.expression = "mul(a,add(b,c))";
$scope.data = {
a: 2,
b: 4,
c: 5
};
var parseFunc = $parse($scope.expression);
$scope.ParsedValue = parseFunc($scope.context, $scope.data);
})
参考文章如下:
https://segmentfault.com/a/1190000002749571