Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
你能在AngularJS表达式中调用函数吗?_Angularjs_Function_Call - Fatal编程技术网

你能在AngularJS表达式中调用函数吗?

你能在AngularJS表达式中调用函数吗?,angularjs,function,call,Angularjs,Function,Call,我正在学习W3School的Angular课程,我很困惑为什么我不能在Angular表达式中调用函数-只是为了好玩,即使如果我后来发现这可能不是最佳实践: <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <script> function add() {

我正在学习W3School的Angular课程,我很困惑为什么我不能在Angular表达式中调用函数-只是为了好玩,即使如果我后来发现这可能不是最佳实践:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script>
function add() { return 5+5 }
</script>
<body>

<div ng-app>
<p>My first expression: {{ add() }}</p>
</div>

</body>
</html>

函数add(){return 5+5}
我的第一个表达式:{{add()}}


您可以,但是函数需要在控制器中定义,因为
{{}
符号就是在控制器中定义的

angular.module('app',[])
.controller('ctrl',function(){
this.add=()=>{
返回5+5;
}
});

{{$ctrl.add()}}

全局函数默认绑定到
窗口
对象。因此,如果在
窗口
对象中有函数,则可以将其直接绑定到控制器的
$scope
并在模板中使用

angular.module('app',[])
.controller('ctrl',函数($scope,$window){
$scope.add=$window.add;
});

函数add(){return 5+5}
{{add()}}

你可以!但是您需要首先在相应的
$scope
中声明函数,因为此函数在您没有的作用域上被调用。你需要通过一些“Hello world”教程来了解它是如何完成的。不是任何函数,而是scope/rootscope中的函数。