$parse和$eval都是用来将表达式转为一个函数
$eval是scope的一个方法,$parse是一种全局可以使用的服务。
从api可以看出来$eval是一种使用当前上下文的特殊$parse
// `$parse`
$parse(expr)(context, locals);
// `$eval`:
// expr:要解析的表达式
// locals:上下文
function(expr, locals) {
return $parse(expr)(this, locals);
}
使用
<!DOCTYPE html>
<html ng-app="App">
<head>
<meta charset="utf-8">
<script src="https://www.linuxidc.com/tools/libs/angular.js/1.7.8/angular.min.js"></script>
</head>
<body ng-controller="Ctrl">
<div>{{sayName}}</div>
<script>
angular.module("App", []).controller("Ctrl", ["$scope","$parse",function($scope,$parse) {
var context = {
"name":"Linux公社"
};
$scope.name = "chenjy";
// ------------- 1 -------------
$scope.sayName = $parse("'my name is '+ name")(context)
// outPut: my name is tom
// ------------- 2 -------------
$scope.sayName = $parse("'my name is '+ name")($scope)
// outPut: my name is chenjy
// ------------- 3 -------------
$scope.sayName = $parse("'my name is '+ name")()
// outPut: my name is
// ------------- 1 -------------
$scope.sayName = $scope.$eval("'my name is '+ name");
// outPut: my name is chenjy
// ------------- 2 -------------
$scope.sayName = $scope.$eval("'my name is '+ name",context);
// outPut: my name is Linux公社
}]);
</script>
</body>
</html>
我们用添加一个可以修改表达式的input,并且监听表达式当值发生变化重新解析
<!DOCTYPE html>
<html ng-app="App">
<head>
<meta charset="utf-8">
<script src="https://www.linuxidc.com/tools/libs/angular.js/1.7.8/angular.min.js"></script>
</head>
<body ng-controller="Ctrl">
<div>{{sayName}}</div>
<input type="text" ng-model="expr" />
<script>
angular.module("App", []).controller("Ctrl", ["$scope", "$parse", function($scope, $parse) {