简体   繁体   English

如何使用$ scope方法在AngularJS控制器中调用函数?

[英]How to call function in AngularJS controller with $scope method?

I have a function inside my controller that I want to be able to call from a $scope method so I can reuse my code only within the controller. 我希望在控制器内部有一个函数,该函数可以从$ scope方法调用,以便仅在控制器内重用代码。 I use the function to clear some input fields. 我使用该功能清除一些输入字段。 I would like to call after a user is inserted as well as I would like to assign it to the a "Clear" button click. 我想在插入用户后调用,也希望将其分配给“清除”按钮单击。 Calling the function after inserting works just fine but assigning the function to the method isn't. 插入后调用函数就可以了,但是不能将函数分配给方法。

If I assign the function directly to the $scope.clearUser method it works but then I can't call it after inserting a user. 如果我直接将函数分配给$ scope.clearUser方法,则它可以工作,但在插入用户后无法调用它。

function clearUser() {
    $scope.EmployeeNumber = '';
    $scope.isAdmin = false;
};

$scope.clearUser = clearUser();    
//also tried $scope.clearUser = this.clearUser();

//$scope.clearUser = function() {
//    $scope.EmployeeNumber = '';
//    $scope.isAdmin = false;
//};

<button ng-click="clearUser()" class="btn btn-default">
    <i class="fa fa-times"></i> Clear
</button>

Omit the () to pass the function: 省略()以传递函数:

$scope.clearUser = clearUser;

Or, create it all at once: 或者,一次创建所有内容:

var clearUser = $scope.clearUser = function() {

}

try to change, 尝试改变

$scope.clearUser = clearUser(); $ scope.clearUser = clearUser();

to

$scope.clearUser = clearUser; $ scope.clearUser = clearUser;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在angularjs控制器范围内调用全局函数回调? - How would I call a global function callback in the scope of a angularjs controller? AngularJS - 我如何使用 $scope 在控制器中调用函数 - AngularJS - how can i call a function in a controller with $scope 如何在AngularJS的另一个控制器中调用/使用$ scope的一个控制器 - How to call/use 1 controller of $scope in another controller in AngularJS AngularJS:从具有隔离范围的指令中调用控制器函数 - AngularJS : Call controller function from a directive with isolated scope 从html调用angularjs控制器中的函数,并且未定义范围变量 - call a function in angularjs controller from html and scope variable is not defined AngularJS:如何从控制器调用在指令范围内定义的函数? - AngularJS: How do I call a function defined in a directive's scope from a controller? 如何从控制器在指令范围内调用函数 - How to call a function on a directive scope from the controller angularjs如何在控制器中进行方法调用 - angularjs How to make method call itself in controller 如何在Ajax调用中调用控制器外部的Angularjs控制器函数 - How to call Angularjs controller function outside the controller in an Ajax call 如何在angularjs的控制器内部调用函数 - How to call function inside controller in angularjs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM