如何在 AngularJS 控制器中调用 javascript 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31197827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I call javascript function in AngularJS controller?
提问by RKS
I have below Javascript functions
我有以下 Javascript 函数
<script type="text/javascript">
function ShowProgress() {
var modal = $('<div />');
modal.addClass("spinmodal");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
}
function HideProgress() {
var loading = $(".loading");
loading.hide();
$(".spinmodal").remove();
}
</script>
now I want to call this ShowProgress()
and HideProgress()
in Angular controller. I want to call ShowProgress()
as soon as deletePrepared
invoked and HideProgress()
below GetAllPrepared
.
现在我要调用此ShowProgress()
并HideProgress()
在角控制器。我想打电话给ShowProgress()
尽快deletePrepared
调用和HideProgress()
下方GetAllPrepared
。
<script type="text/javascript">
app.controller("myCntrl", function ($scope, angularService, $modal) {
$scope.deletePrepared = function (itm) {
var getData = angularService.DeletePrepared(itm.ProductId);
getData.then(function (msg) {
GetAllPrepared();
}, function () {
alert('Error in Deleting Record');
});
}
});
</script>
回答by Shashank Agrawal
Simply call those methods:
只需调用这些方法:
app.controller("myCntrl", function ($scope, angularService, $modal) {
$scope.deletePrepared = function (itm) {
ShowProgress();
var getData = angularService.DeletePrepared(itm.ProductId);
getData.then(function (msg) {
HideProgress();
GetAllPrepared();
}, function () {
alert('Error in Deleting Record');
});
}
});
Tip: Use Angular directives to do DOM manipulation and you don't require any jQuery code for DOM manipulation, Angular is sufficient for it.
提示:使用 Angular 指令进行 DOM 操作,不需要任何 jQuery 代码来操作 DOM,Angular 就足够了。
回答by imbond
You can create a service and plug it inside the controller. By this, you can reuse the function in multiple controllers.
您可以创建一个服务并将其插入到控制器中。这样,您可以在多个控制器中重用该功能。
Example,
例子,
/* Controller */
angular.module('appApp')
.controller('myCtrl', function ($scope, Modal) {
Modal.openModal("myBtn");
}
/* Service */
angular.module('appApp')
.factory('Modal', function() {
return {
openModal: function(btnId) {
// Java script code goes here...
}
};
});
P.S: Don't forget to add service in your index.html file.
PS:不要忘记在 index.html 文件中添加服务。
I hope this helps!
我希望这有帮助!