Is this possible to call simple JS method from Angular JS controller method?

We have a controller on controller.js file.

angular.module('MyModule', [])
    .controller('MyController', function ($scope) {
    $scope.myfunction = function (data) {
        alert("---" + data);
        // Test(); Calling java script method
    };
 });

In other file common.js we have defined

function Test()
{
  alert("Test Method is Calling");
 }

Both files are including in html, but we are not able to call legacy javascript code from controller method.

Kindly assist.

Answers


Works just fine, make sure your other file is loaded:

angular.module('MyModule', [])
    .controller('MyController', function ($scope) {
    $scope.myfunction = function (data) {
        alert("---" + data);
        Test(); // Calling java script method
    };
 });


function Test()
{
  alert("Test Method is Calling");
 }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyModule" ng-controller="MyController">
<button ng-click="myfunction('Hey')">Call extenal function</button>
</div>

I would not recommend mixing AngularJS code with legacy JS code. In your case, if Test() is some kind of function that you are going to use often I would encapsulate it in a service and inject it into your controller

angular.module('MyModule')
    .factory('Utilities', function ($window) {
        return {
           Test : function() {
                $window.alert('Blah blah');
            }
        };
    });

And then in your controller

angular.module('MyModule', [])
    .controller('MyController', function ($scope, Utilities) {
    $scope.myfunction = function (data) {
        Utilities.Test();
    };
 });

This is pure AngularJS methodology


Yes you can use function of your external or internal java-script, but this is not good to mix the function within angular controller. If still you need it you can create a service and through service you can call the external java-script method.

var app = angular.module('plunker', []);

app.service('MyService', function() {

    this.callAlert = myTest();

});

app.controller('MainCtrl', function($scope, MyService) {
  $scope.name = 'World';

  $scope.callService = MyService.callAlert;
});


function myTest(){
  alert('Hello world');
}

Here's plunker link Plunker Demo


Need Your Help

constexpr, static_assert, and inlining

c++ c++11 inline constexpr static-assert

I previously asked about function overloading based on whether the arguments are constexpr. I'm trying to work around the disappointing answer to that question to make a smarter assert function. Th...

Visual C# Express 2008

expand collapse

when coding in Visual C# Express 2008 you can expand/collapse code segments using the +/- symbols on the left hand corner of the text-editor. These appear automatically when a function is created.