简体   繁体   中英

How can I call javascript function in AngularJS controller?

I have below Javascript functions

<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 .

<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>

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.

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...
      }
    };
});

PS: Don't forget to add service in your index.html file.

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM