在AngularJs中向控制器添加功能 [英] Adding function to controllers in AngularJs

查看:84
本文介绍了在AngularJs中向控制器添加功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将功能添加到angularJS的控制器中,我认为应该可以正常工作,但遗憾的是没有.

I'm trying to add function to controller in angularJS, the way I think should be working but sadly not.

这是我的代码.

//this is working.
$scope.adddata = function () {
    $scope.names.push({name:$scope.newdata.name,city:$scope.newdata.city});
    //$scope.names.push($scope.newdata);
}


//this is not working
function adddata() {
$scope.names.push({name:$scope.newdata.name,city:$scope.newdata.city});
//$scope.names.push($scope.newdata);
}
$scope.adddata = adddata();

以上两个函数均在控制器的定义中,因此$ scope变量可用.

Both functions above are in the definition of controller, hence $scope variable is available.

我只能使用 $ scope.functionname = functionname(){....}

或者我可以创建一个函数,然后将其分配给控制器/作用域.

or I can create a function and later assign it to controller / scope.

推荐答案

执行 $ scope.adddata = adddata; (无括号).使用括号会将调用 adddata()结果分配给范围变量,该变量是未定义的( adddata()不返回值).

Do $scope.adddata = adddata; (no parentheses). Using the parentheses will assign the result of calling adddata() to the scope variable, which is undefined (adddata() does not return a value).

这篇关于在AngularJs中向控制器添加功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆